【发布时间】:2019-06-09 06:28:33
【问题描述】:
我一直想知道为什么向 mongoose findOneAndUpdate 函数添加回调会导致将数据两次保存到 DB 中?
public async addPersonAsFavorite(userId: string, friendId: string) {
if (!await this.isPersonAlreadyFriend(userId, friendId)) {
const friendList = FriendsList.findOneAndUpdate(
{ _id: userId },
{ $push: { friendsList: friendId } },
{ upsert: true, new: true },
(err, data) => {
if (err) console.error(err);
return data;
}
);
return friendList;
}}
public async isPersonAlreadyFriend(userId: string, friendId: string) {
let isFriendFound = false;
await FriendsList.findById(userId, (err, data) => {
if (data) {
console.log(data.friendsList);
}
if (err) console.error(err);
if (data && data.friendsList.indexOf(friendId) > -1) {
isFriendFound = true;
console.log('already friend');
} else {
console.log('not friend');
isFriendFound = false;
}
})
return isFriendFound;
}
如果我删除回调,数据只会保存一次。
编辑:添加了第二段代码和新问题。 如果有人向按钮发送垃圾邮件以添加朋友。该朋友将被添加多次,因为在添加第一个朋友之前,可以进行检查以防止这种情况,它已经多次添加了该人。
在允许再次调用该函数之前,我如何确保它完成了对 DB 的写入?
【问题讨论】:
-
你那里为什么有回调..?只需添加等待..
标签: javascript mongodb express mongoose