我一直想知道为什么给 mongoose findOneAndUpdate 函数添加回调会导致将数据保存两次到数据库?
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;
}
如果我删除回调,数据只会保存一次。
编辑:添加了第二段代码和新问题。 如果有人向按钮发送垃圾邮件以添加 friend 。 friend 将被添加多次,因为在添加第一个 friend 之前,可以进行检查以防止这种情况,它已经多次添加了该人。
我怎样才能确保它在允许再次调用该函数之前完成对数据库的写入?
最佳答案
也许问题出在 isPersonAlreadyFriend 方法中,因为您正尝试使用 async await 调用它,但随后您传递了一个回调,这使得该方法不返回 promise 。在 mongodb 中使用 promises 的正确方法应该是这样的:
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;
}
试试这个,如果有帮助请告诉我
关于javascript - 为什么使用 Mongoose 回调会导致两次保存数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54195550/