search

Home  >  Q&A  >  body text

mongodb - 如何根据嵌套的属性值查找(第一层属性值是数组)?

示例代码如下:

var UserSchema = new Schema({
    interactions: [{
        interactor: {
            type: Schema.Types.ObjectId,
            ref: 'User'
        }
    }]
});

我现在想根据userId匹配所有interactor的值为userId的interaction,用mongoose如何能做到呢?

巴扎黑巴扎黑2765 days ago684

reply all(1)I'll reply

  • 伊谢尔伦

    伊谢尔伦2017-04-24 09:13:50

    I found a solution to the matching problem, which is very intuitive:

    User.find({
        'interactions.interactor': mongoose.Types.ObjectId(user._id)
    }, function (err, users) {
    }
    

    But in the callback function, I will update multiple matching users. How should I save it after the update? If there is no users.save() method, do I have to write loop save myself?

    reply
    0
  • Cancelreply