这是我的代码,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 [];
}
}
帮助?
答案 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);
})