简体   繁体   English

更新返回匹配

[英]update return matched

How can i make this update work?我怎样才能使这个update工作?

current error:当前错误:

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

i also tried to put $, but then i get:我也试图把 $,但后来我得到:

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

code:代码:

 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);
    });

model:模型:

  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

Looking at the documentation here is how the positional operator $ handle arrays :查看此处的文档是位置运算符 $ 处理数组的方式:

Nested Arrays嵌套数组

The positional $ operator cannot be used for queries which traverse more than one array, such as queries that traverse arrays nested within other arrays, because the replacement for the $ placeholder is a single value位置 $ 运算符不能用于遍历多个数组的查询,例如遍历嵌套在其他数组中的数组的查询,因为 $ 占位符的替换是单个值


So you cannot perform the increment that way.所以你不能以这种方式执行增量。 You should retrieve the data, modify it programmatically and then save the change.您应该检索数据,以编程方式对其进行修改,然后保存更改。

For example :例如 :

// 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 ... 
  });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM