更新返回匹配

时间:2017-10-05 07:45:35

标签: javascript database mongodb mongoose

如何使update工作?

当前错误:

MongoError: cannot use the part (cartheft of crimes.0.cartheft.chance) to traverse the element 

我也试图把$,但后来我得到了:

(node:10360) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 2): MongoError: Too many positional (i.e. '$') elements found in path 'crimes.$.cartheft.$.chance'

代码:

 cartheft_crime.update({
        userid: req.user._id,
        "crimes.location": 1,
        "crimes.cartheft.theftid" : 1,
    }, {$inc: {"crimes.$.cartheft.chance": 1000}}).then(function (response) {
        res.json(response);
    });

模型:

  userid : String,
    crimes: [{
        location: {type: Number, default: 1},
        lastcartheft: {
            time: {type: Number, default: 1},
            type: {type: Number, default: 1},
        },
        cartheft: [
            {
                id: {type: Number, default: 1},
                theftid: {type: Number, default: 1},
                chance: {type: Number, default: 200},
                success: {type: Number, default: 0},
                failure: {type: Number, default: 0},
            },
        ],
    }],
    ip: String

1 个答案:

答案 0 :(得分:1)

查看documentation这里的位置运算符$ handle arrays:

  

嵌套数组

     

位置$运算符不能用于遍历的查询   多个数组,例如遍历嵌套数组的查询   在其他数组中,因为$ placeholder的替换是   单个值

所以你无法以这种方式执行增量。您应检索数据,以编程方式对其进行修改,然后保存更改。

例如:

// Get the user data
cartheft_crime.findOne({
  userid: req.user._id,
})
  .then((ret) => {
    // We have no user behind req.user._id
    if (!ret) throw new Error('Cannot find the user');

    // Modify the data 
    const user_obj = ret;

    // Get the right crime to modify
    const right_crime = user_obj.crimes.find(x => x.location === 1);

    // Cannot find it
    if (!right_crime) throw new Error('Cannot find the appropriate crime');

    // Get the right cartheft to modify
    const right_cartheft = right_crime.cartheft.find(x => x.theftid === 1);

    // Cannot find it
    if (!right_cartheft) throw new Error('Cannot find the appropriate cartheft');

    // Finally modify the data
    right_cartheft.chance += 1;

    // Save the data
    return user_obj.save();
  })
  .then(() => {
    // It's done !
  })
  .catch((err) => {
    // Send the error ... 
  });