簡體   English   中英

Mongoose (JavaScript) 中的文檔問題

[英]Issues with the Documents in Mongoose (JavaScript)

所以我正在制作一個不和諧的機器人,但我在貓鼬上遇到了一些問題。 所以我想要的基本上是,用戶發送一條消息來保存一個包含他的一些信息的文檔,但是如果已經有一個包含他的信息的文檔,它將停止該過程並返回。 所以我試過這個:

      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 語句中失敗。 我已經嘗試了很多東西,但它不起作用。 我認為這個問題的解決方案與異步函數有關,但我不確定,我對異步進程了解不多。

提前致謝!

問題是您將 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]

您可能需要考慮使用 async/await 來減少回調。 您還可以考慮使用唯一索引來避免將來出現多個請求。 嘗試保存同一文檔兩次時,使用唯一索引將引發錯誤。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM