2017-10-05 80 views
1

我如何使这个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

望着这里的documentation是怎样的位置操作$处理数组:

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


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

例如:

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

怎么会那么正确的方式来做到这一点呢? – maria