如何在mongoose上更新多个模型并将更新后的模型作为数组返回?

时间:2018-04-23 12:51:02

标签: javascript mongoose

这是我的代码,ids arg是一组模型ID,我希望状态字段设置为true:

async function seenAllNotification(ids) {
  return await Notification.update({ _id: { $in: ids }}, { status: true }, { multi: true });
}
这会有用吗?我也希望它将模型作为一个对象数组返回,我也试过这个,这不起作用:

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 [];
  }
}

帮助?

1 个答案:

答案 0 :(得分:0)

有关少数事情的详细信息

1. Notification.update返回此json对象{ n: 4, nModified: 0, ok: 1 }

  • n是目标行数
  • nModified是已修改行数
  • ok是更新成功/错误

2.以async为前缀的方法将返回一个承诺。可以使用.then回调

调用此方法

以下是使用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")
    }
};

请注意,我已使用json对象返回了find和update对象。

return {find,update}将自动翻译为return {find:find, update:update}

如果需要在响应对象中发送任何这些细节以进行渲染,则返回find,update可能很有用。

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