猫鼬(JavaScript)中的文档问题

时间:2020-09-07 16:46:13

标签: javascript node.js database mongodb mongoose

所以我正在为不和谐的机器人做准备,但是我在Mongoose上遇到了一些问题。所以我想要的基本上是,用户发送一条消息来保存带有他的一些信息的文档,但是如果已经有一个带有他的信息的文档,它将停止返回过程。所以我尝试了这个:

      function main(message){
        // So first user sends a message to store some data about him
        let author = message.author //this is discord.js syntax, basically it returns the author of a message
        let id = author.id //also discord.js syntax, returns the id from the user, in this case the author variable above
       
       let check = logUser.findOne({userId : [id]}).exec().then(res => {
            if (res) return true;
            else return false;
        })} // So if there is a Document with the id of the author of the message it will return true, else it returns false

        if (check === true) return console.log("This User has already a Document with his info saved"); 
//so if the user has already a Document with his info it will return and stop the action of saving his Data
//everything from this point is basic Mongoose Syntax, to make a Document with User data
        const theUser = new logUser({
            _id : mongoose.Types.ObjectId(),
            userName : author.username,
            userId : author.id,
            currency : 0
        })
        theUser.save()

        .then(result => console.log(result))
        .catch(err => console.log(err))

        console.log(`User ${author.username} was stored into the database!`)
}

在if语句中失败,该语句检查用户是否已经拥有带有其信息的Document。我已经尝试了多种方法,但是没有用。 我认为该问题的解决方案与异步功能有关,但我不确定,而且我对异步过程了解的不多。

谢谢!

1 个答案:

答案 0 :(得分:1)

问题是您将logUser.findOne视为同步。像下面这样在findOne回调中执行检查:

  function main(message){
    // So first user sends a message to store some data about him
    let author = message.author //this is discord.js syntax, basically it returns the author of a message
    let id = author.id //also discord.js syntax, returns the id from the user, in this case the author variable above
    
    logUser.findOne({userId : [id]}).exec().then(res => {
      let check = Boolean(res);
      if (check === true)
        return console.log("This User has already a Document with his info saved");

      const theUser = new logUser({
        _id : mongoose.Types.ObjectId(),
        userName : author.username,
        userId : author.id,
        currency : 0
      });

      theUser.save()
        .then(result => {
          console.log(result);
          console.log(`User ${author.username} was stored into the database!`)
        })
        .catch(err => console.log(err))
    });
}

您是否有意将ID包裹在数组中?我不知道您的架构,但看起来很奇怪,可能会助您一臂之力。 userId : [id]

您可能要考虑异步/等待以减少回调。您还可以考虑使用唯一索引以避免将来出现多个请求。尝试两次保存同一文档时,使用唯一索引将引发错误。

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await https://docs.mongodb.com/manual/core/index-unique/