为什么使用猫鼬回调会导致两次保存数据? [英] Why does using mongoose callback result in saving data twice?

查看:56
本文介绍了为什么使用猫鼬回调会导致两次保存数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直想知道为什么向Mongoose findOneAndUpdate函数添加回调会导致两次将数据保存到数据库?

I have been wondering why adding a callback to the mongoose findOneAndUpdate function results in saving the data twice to the 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;
  }

如果我删除回调,则数据只会保存一次.

If i remove the callback, the data only gets saved once.

添加了第二段代码和新问题. 如果有人发送垃圾邮件,则添加朋友.该朋友将被添加多次,因为在添加第一个朋友之前,可以进行检查以防止它已经多次添加该人.

added second piece of code and new question. If someone spams the button to add friend. The friend will be added multiple times because before the first friend is added and the check can be done to prevent this it has already added the person multiple times.

在允许再次调用该函数之前,如何确保它完成了对DB的写操作?

How can i make sure that it completes the write to the DB before allowing the function to be called again?

推荐答案

也许问题出在isPersonAlreadyFriend方法中,因为您试图使用异步等待来调用它,但是随后您传递了一个回调,这使得该方法未返回a承诺.在mongodb中使用promise的严格方法应该是这样的:

Maybe the problem is in isPersonAlreadyFriend method, because you are trying to call it using async await but then you are passing a callback, what makes the method not return a promise. The rigth way to use promises with mongodb should be something like this:

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;
  }

尝试一下,让我知道是否有帮助

Try with this and let me know if it helps

这篇关于为什么使用猫鼬回调会导致两次保存数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆