2017-10-05 3 views
1

Comment puis-je faire ce update de travail?mise à jour retour correspondant

erreur actuelle:

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

J'ai aussi essayé de mettre $, mais je reçois:

(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); 
    }); 
modèle

:

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 

Répondre

1

En regardant le documentation voici comment l'opérateur de position des réseaux de poignée de $:

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


vous ne pouvez donc pas effectuer l'augmentation de cette façon. Vous devez récupérer les données, les modifier par programme, puis enregistrer la modification.

Par exemple:

// 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

Comment alors la bonne façon d'accomplir ce soit? – maria