【问题标题】:Mongoose, Add/Update data to a set of documents of a collectionMongoose,将数据添加/更新到集合的一组文档中
【发布时间】:2016-10-28 16:53:34
【问题描述】:

大家好,我的问题是这样的:

我的 Categories 模型如下所示:

schema: {   
    _id: String,
    name: String,
    overview: String,
    courses: [
        {
            _id: String,
            name: String
        }
    ]
}

我记录了多个类别,在上面的集合中Categories

我需要什么

我有一个 [ 数组 ]Categories._id,如下所示:

[
  '5812f3cb04700f2563c0e56a',
  '5812f3ff04700f2563c0e56b',
  ...
]

我想要的只是PUSH这个对象{_id:5812f3ff04700f2563c0e56b, name:'SOMETHING' }@的array中列出的所有文档987654328@

我尝试了什么

Categories.update({
        '_id': {
            $in : array_of_IDs
        } 
    },
    {
        $push :{
            'courses':{ _id: ret._id , name: ret.title }
        }
    }, function(err, respp){
        if(err) return res.negotiate(err);
        else{
            req.addFlash('success', 'Categories updated successfully.');
            return res.redirect('/new-course');
        }
    }
);

以上代码仅更新一个集合(ID 数组中第一个 ID 的集合)

请帮忙!

谢谢

【问题讨论】:

    标签: node.js mongodb mongoose mongoose-schema


    【解决方案1】:

    可以尝试使用multi: true 作为选项

    Categories.update({
            '_id': {
                $in : array_of_IDs
            } 
        },
        {
            $push :{
                'courses':{ _id: ret._id , name: ret.title }
            }
        },{ multi: true }, function(err, respp){
            //....
        }
    );
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-08
      • 1970-01-01
      • 2014-11-03
      • 1970-01-01
      • 2016-02-27
      • 1970-01-01
      • 2021-08-06
      • 1970-01-01
      相关资源
      最近更新 更多