猫鼬,从子文档中提取 [英] Mongoose, pull from subdocument

查看:57
本文介绍了猫鼬,从子文档中提取的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的文档:

{ 
  password: '87654321',
  title: 'Organization A',
  members: 
   [ { tier: 1,
       joinedDate: Sun May 12 2013 00:00:00 GMT+0200 (CEST),
       user: 543fc462ed385e5e77a98d56 
     },
     { tier: 2,
       joinedDate: Sat May 11 2013 00:00:00 GMT+0200 (CEST),
       user: 543fc462ed385e5e77a98d57 
     },
     { tier: 3,
       joinedDate: Fri May 10 2013 00:00:00 GMT+0200 (CEST),
       user: 543fc462ed385e5e77a98d58 
     }
    ]
}

我想编写一个查询来提取具有给定用户_.id的成员

I want to write a query that pulls a member with a given user _.id

pull命令可能是我应该使用的

The pull command is probably what I should use

http://mongoosejs.com/docs/api.html#types_array_MongooseArray-pull

mongoose.model('organization').findOne({_id:user.organization}, function(err, org){
      org.members.pull({'user._id':user._id});
      org.save();
    })

它不起作用.我在做什么错了?

It's not working. What am I doing wrong?

更新

我的模式:

var organizationSchema = new Schema({
  title: String,
  password: { type: String, required: true, index: { unique: true } },
  members: [
    {
      tier: { type: Number, required: true, min:1, max:4},
      joinedDate: Date,
      user:{
        type: Schema.ObjectId,
        ref: 'user',
        required: true,
        unique:true
      }
    }
  ]
});

推荐答案

看来,MongooseArray#pull方法仅在您的元素具有_id属性时才有效.

It appears that the MongooseArray#pull method only works if your elements have _id properties.

我发现使用直接调用update的方式来避免这些意外情况更容易:

I find it easier to use direct calls to update to avoid these sorts of surprises:

mongoose.model('organization').update(
    {_id: user.organization},
    {$pull: {members: {user: user._id}}},
    function(err, numAffected) { ... }
);

这篇关于猫鼬,从子文档中提取的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆