简体   繁体   中英

How to update multiple models on mongoose and return updated models as an array?

this is my code, the ids arg is an array of ids of models i wanted the status field set to true:

async function seenAllNotification(ids) {
  return await Notification.update({ _id: { $in: ids }}, { status: true }, { multi: true });
}

would this work? i also wanted it to return the models as an array of objects, I also tried this, which doesn't work:

async function seenAllNotification(ids) {
  const notifs = await Notification.update({ _id: { $in: ids }}, { seen: true })
  if (notifs) {
    const allNotifs = await Notification.find({ '_id': { $in: ids } });
    return allNotifs;
  } else {
    return [];
  }
}

Help?

Details on few things

1. Notification.update returns this json object { n: 4, nModified: 0, ok: 1 }

  • n is number of targeted rows
  • nModified is number of modified rows
  • ok is update success/error

2.A method prefixed with async will return a promise. This method could be invoked using .then callback

Below is the code using async await

var seenAllNotification = async ()=>{
    var find = null;
    var update = await Notification.update({_id : ids},{ status: true },{ multi: true });
    //{ n: 4, nModified: 0, ok: 1 }
    if(update.n == ids.length){
        find = await Notification.find({_id : ids});
        return {find,update};
    }
    else{
        throw new Error("some ids are not updated")
    }
};

Notice that i have returned both find and update object using a json object.

return {find,update} will be automatically translated into return {find:find, update:update}

Returning find,update could be useful if its necessary to send any of these details in response object for rendering.

seenAllNotification().then((response)=>{
   console.log("updated elements ",response.find);
}).catch((err)=>{
    console.log("err ",err);
})

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