javascript - 为什么使用 Mongoose 回调会导致两次保存数据?

标签 javascript mongodb express mongoose

我一直想知道为什么给 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/

相关文章:

java - Mongo打开了太多的连接

javascript - 在 JavaScript 和 vxml 中使用多个转接号码

javascript 日期差异 NaN

mongodb - 如何从另一个容器应用程序连接到 mongodb 作为 docker 镜像

javascript - 连接到多个数据库的仅 Meteor 服务器 Web 应用程序

node.js - 引用错误: number is not defined in MEAN

mysql - ORM 使用什么?

node.js - swagger-ui-express 不在浏览器中呈现,但在 Postman 中具有响应正文

javascript - 在 Javascript 中将小数添加到字符串

React/Redux 中的 Javascript 函数语法