【问题标题】:Mongoose: how to pull from array in document instanceMongoose:如何从文档实例中的数组中提取
【发布时间】: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


【解决方案1】:

我使用文档中指定的org.candidates.pull(id) 解决了这个问题。查询参数似乎不起作用。

【讨论】:

    猜你喜欢
    • 2015-02-18
    • 2021-09-02
    • 1970-01-01
    • 2022-10-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-18
    • 2022-07-25
    • 2017-09-17
    相关资源
    最近更新 更多