如何在mongodb中更新文件数组?

时间:2016-05-17 14:30:47

标签: arrays angularjs mongodb express

我有AdminGroupOperation模型,如下所示:

var AdminGroupOperation = new mongoose.Schema({
    module    : String,
    adminGroup: {type: mongoose.Schema.Types.ObjectId, ref: 'AdminGroup'},
    operations: [{type: mongoose.Schema.Types.ObjectId, ref: 'Operation'}],

    recycled: Number
});

和我的操作模型如下:

var Operation = new mongoose.Schema({
    name : String,
    value: Boolean,


    recycled: Number
});

如何在AdminGroupOperations模型中更新操作数组?在我的api我有类似的东西,但这不会工作..

exports.update = function (req, res, next) {
    var data = req.body;

    AdminGroupOperation.findByIdAndUpdate({"_id": req.params.id}, {
            module    : data.module,
            adminGroup: data.adminGroup._id,
            operations: data.$.operations_id
        },
        {new: true},

        function (err, secoperation) {
            if (err) {
                return next(err);
            }
            secoperation.save(function (err) {
                if (err) {
                    return next(err);
                }
            });

            res.json({'status': 'updated', 'ID': req.params.id});
        })
};

1 个答案:

答案 0 :(得分:0)

你必须在没有请求的情况下使用id,我的意思是:

 AdminGroupOperation.findByIdAndUpdate req.params.id, { $set:{
        module    : data.module,
        adminGroup: data.adminGroup._id,
        operations: data.$.operations_id
    }}, {new: true},

    function (err, secoperation) {
        if (err) {
            return next(err);
        }
        secoperation.save(function (err) {
            if (err) {
                return next(err);
            }
        });

        res.json({'status': 'updated', 'ID': req.params.id});
    })
  };

我不确定选项:{new:true},或者您只需使用更新来使用请求来查找ID