因此,我需要删除引用/ObjectId数组中的元素,但删除条件将基于引用中的字段。
例如,我有如下模式:
const UserSchema = new mongoose.Schema({
firstName: String,
lastName: String,
homeFeeds:[{type: Schema.Types.ObjectId, requried: true, ref: "Activity"}];
}); // User , is the referenece name
const ActivitySchema = new mongoose.Schema({
requester: {type: Schema.Types.ObjectId, requried: true, ref: "User"},
message: String,
recipient: {type: Schema.Types.ObjectId, requried: true, ref: "User"},
}) // Activity, is the reference name
现在,我需要为用户删除一些homeFeeds,而应该删除的homeFeeds需要由特定的请求者删除。这需要首先填充homeFeeds("活动"的数组(字段,然后使用$pull运算符更新它,条件是"活动"请求者匹配某个用户。
我不想先读取数据并在Nodejs/后端代码中进行过滤,因为数组可能很长。
理想情况下,我需要这样的东西:
await User.find({_id: ID})
.populate("homeFeeds", "requester")
.updateMany({
$pull: {
homeFeeds.requester: ID
}
});
但它不起作用,如果有人能帮我解决这个问题,我真的很感激?
感谢
MongoDB在6.0.1版本的更新中不支持$lookup
。
MongoServerError:$lookup不允许在更新中使用。
不过,这与Mongoose
的populate
无关,因为populate
不依赖于$lookup
,并触发额外的查询来获得结果。看看这里。因此,即使你可以实现你想要的,即避免在nodejs/后端获取大数组,使用mongoose
也会在幕后为你做同样的事情,这违背了你的目的。
然而,您应该在Mongoose的官方github页面上提出一个问题,并期待得到回应。