简体   繁体   中英

Mongoose findOneAndUpdate on array of subdocuments

I'm trying to replace an array of sub-documents with a new copy of the array.

Something like...

var products = productUrlsData;   //new array of documents

var srid = the_correct_id;

StoreRequest.findOneAndUpdate({_id: srid}, {$set: {products: products}}, {returnNewDocument : true}).then(function(sr) {
        return res.json({ sr: sr});  //is not modified
}).catch(function(err) {
        return res.json({err: err});
})

The products var has the correct modifications, but the returned object, as well as the document in the db, are not being modified. Is this not the correct way to replace a field which is an array of subdocuments? If not, what is?

I am a bit late to the party plus I am really in a hurry -- but should be:

StoreRequest.updateOne(
        { _id: srid },
        { $set: { 'products.$': products }},
        { new: true });

I couldn't make it work with findOneAndUpdate but the above does work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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