javascript - 为什么使用猫鼬回调会导致两次保存数据?
问题描述
我一直想知道为什么向 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;
}
如果我删除回调,数据只会保存一次。
编辑:添加了第二段代码和新问题。如果有人向按钮发送垃圾邮件以添加朋友。朋友将被添加多次,因为在添加第一个朋友之前,可以进行检查以防止这种情况,它已经多次添加了该人。
在允许再次调用该函数之前,我如何确保它完成了对 DB 的写入?
解决方案
也许问题出在 isPersonAlreadyFriend 方法中,因为您尝试使用 async await 调用它,但随后您传递了一个回调,这使得该方法不返回承诺。在 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;
}
试试这个,让我知道它是否有帮助
推荐阅读
- python - 如何从 Python 对 AWS Lambda 中的 Google API 进行身份验证
- google-bigquery - 左不包括与 BigQuery 的连接
- javascript - 根据列值确定控制台日志中的值
- javascript - 将 jQuery Modal Cookie 设置为 7 天后过期
- python - 删除 - 使用正则表达式
- c++ - 我想制作一个程序,将用户的输入分成 3 个循环链表。但我面临返回值 3221225725 错误
- django - Vuejs 中的请求返回的响应与来自 django rest-framework 后端的 Postman 不同
- methods - Rust 的特征对象如何处理移动实例的方法?
- azure-data-factory - 如何获取 ADF 中 JSON 数组的计数?
- python-3.x - 一个热编码器,用于多个单词的分类变量