为什么使用mongoose回调会导致两次保存数据



我一直在想,为什么向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的写入?

也许问题出在isPersonAlreadyFriend方法中,因为您试图使用异步等待来调用它,但随后又传递了一个回调,这使得该方法不会返回promise。在mongodb中使用promise的正确方法应该是这样的:

public async isPersonAlreadyFriend(userId: string, friendId: string) {
let isFriendFound = false;
const data = await FriendsList.findById(userId);
if (data) {
console.log(data.friendsList);
}
if (data && data.friendsList.indexOf(friendId) > -1) {
isFriendFound = true;
console.log('already friend');
} else {
console.log('not friend');
isFriendFound = false;
}
return isFriendFound;
}

试试这个,让我知道它是否有助于

最新更新