【问题标题】:update return matched更新返回匹配
【发布时间】:2023-04-07 17:49:02
【问题描述】:

我怎样才能使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

【问题讨论】:

    标签: javascript database mongodb mongoose


    【解决方案1】:

    看看documentation这里是位置运算符$如何处理数组:

    嵌套数组

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


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

    例如:

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

    【讨论】:

    • 那么正确的方法是什么?
    猜你喜欢
    • 1970-01-01
    • 2013-01-14
    • 2015-12-23
    • 1970-01-01
    • 1970-01-01
    • 2017-02-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多