为什么参数multi在mongo请求中不起作用?

时间:2018-08-05 16:02:25

标签: javascript mongodb mongoose

我尝试通过一个请求更新mongo集合中的多个项目:

// [1, 2, 3] - numbers array.
const days = req.body.days;

const updated = await Item.update(
    {shift: shiftId, day: {$in: days}},
    {multi : true},
    {update: {
        name: 'one value for all objects witch corresponding condition',
    },
    function(err, docs) {
        console.log(docs);
    }
);

此项目模式:

const itemSchema = new Schema({
    shift: {
        ref: 'shift',
        type: Schema.Types.ObjectId,
        required: true
    },
    day: {
        type: Number,
        required: true
    },
    name: {
        type: String
    }
});

但是随后我将此代码称为仅更新一个对象。 我有许多Items和相同的shift。但是每个Item都有自己独特的一天,我需要更新所有以天为单位的Items

例如,如果我们有shiftId = 'abc'days = [1, 2],我需要更新所有具有shiftId = 'abc'和都有day = 1 OR day = 2的商品。

为什么在我设置{multi : true}的同时我的解决方案有意外的行为并且仅更新一个对象?如何解决?谢谢。

1 个答案:

答案 0 :(得分:1)

multi: true是更新查询中的最后一个参数,您已将其用作第二个参数。

因此,您必须在最后一个参数中使用multi: true,并且需要使用$set来更新字段。

const updated = await Item.update(
  { "shift": shiftId, "day": { "$in": days }},
  { "$set": { "name": "one value for all objects witch corresponding condition" }},
  { "multi": true }
)