【发布时间】:2015-06-23 13:31:02
【问题描述】:
假设我在 Mongoose 中有以下架构:
var OrganisationSchema = mongoose.Schema({
name: { type: String },
users: [ UserSchema ]
});
var UserSchema = mongoose.Schema({
name: { type: String, required: true },
email: { type: String, required: true }
});
我在猫鼬的docs看到了这个例子
doc.array.pull(ObjectId)
doc.array.pull({ _id: 'someId' })
doc.array.pull(36)
doc.array.pull('tag 1', 'tag 2')
所以我想知道为什么这个功能不起作用:
OrgSchema.methods.removeUser = function(mail, onRemoveError, onRemoveSucess) {
var org = this;
org.users.pull({email: mail});
org.save(function(err) {
if(err) {
onRemoveError(err);
} else {
onRemoveSuccess(org); // Gets called but has not removed the user
}
});
};
这种pull 不起作用,我想知道为什么? stackoverflow 上的大多数问题线程都参考了 mongodb pull 方法来做这种事情:
Org.update( { _id: orgid }, { $pull: { candidates: { email: mail }}});
这是正确的方法吗?我不能直接拉文档数组吗?
【问题讨论】:
-
我相信你是在正确的轨道上。在文档级别实现方法会非常高效。
-
@ZeMoon 我在尝试此实现后编辑了我的问题。
-
在
org.users.pull()之后记录org.users。你的改变发生了吗? -
使用
org.candidates.pull(id)解决了这个问题。我可以使用 id 而不是查询:{email: mail} -
好的。 mongoose 方法只需要一个 id。如果你想基于查询,你将不得不使用更新。
标签: mongoose