【问题标题】:Data is not saving to MongoDB using the Mongoose findOneAndUpdate Function数据未使用 Mongoose findOneAndUpdate 函数保存到 MongoDB
【发布时间】:2020-08-10 04:38:26
【问题描述】:

我正在使用 Mongoose 与 MongoDB 数据库进行交互。

我将它用于不和谐机器人。

如果用户具有该角色,我正在尝试将数据库中的布尔值 activated 更改为 true

(代码如下)

当我尝试运行该函数时没有错误,只是没有任何反应,并且数据库中的更改没有影响。 数据库已连接并正在工作,并且用户具有完全权限。

let role = call.message.guild.roles.get('702210416012689478')

            if(!call.message.member.roles.has(role.id))
                return;

            call.client.botLoginData.find( {clientID: call.args[0] }, (err, docs) => {
                if(docs.length === 0)
                    return call.message.channel.send(`Couldn't find a client with that ID.`);

                call.client.botLoginData.findOneAndUpdate( { clientID: call.args[0]}, { activated: true });
                call.message.channel.send(`I have successfully updated that bot. Please allow up to 10 mins to propagate, and then restart the bot.`)
            }).catch(error => {
                call.message.channel.send(error)
            })

我是 Mongoose/Mongo 的新手,所以如果我做错了什么,请告诉我

提前致谢。

【问题讨论】:

  • const query = { clientID: call.args[0] }; const update = { $set: { activated: true } }; // Return updated document const options = { new: true }; call.client.botLoginData.findOneAndUpdate(query, update, options, (err, doc) => { all.message.channel.send('I have successfully updated that bot. Please allow up to 10 mins to propagate, and then restart the bot.'); }); 重写到这个
  • @KunalMukherjee 这行得通,但是每次更新一条数据都需要所有这些步骤?我认为 Mongo 不适合我
  • 不,您可以更新任意数量的字段
  • @KunalMukherjee 不,我的意思是有没有更简单的方法可以做到这一点?
  • 定义更简单?

标签: node.js mongodb mongoose discord discord.js


【解决方案1】:

您需要像这样添加带有更新对象的 $set:

call.client.botLoginData.findOneAndUpdate( { clientID: call.args[0]}, {$set:{ activated: true }}, {new:true});

要了解更多关于$set的信息请查看this

【讨论】:

  • 补充说,同样的事情没有发生。数据库中没有反映任何变化
  • 编辑了答案,用 new: true 它提供了更新的文档。
  • 不,仍然没有保存我检查了用户的权限,它有 Atlas 管理员,所以我非常困惑。数据仍然没有错误或变化,
  • @thetechguy61705 如果另一个正在工作,我不明白为什么这个没有工作。有什么想法吗?
  • 不知道哈哈。我觉得自己喜欢猫鼬,有时会选择自己喜欢做的​​事情。
【解决方案2】:

正如@KunalMukherjee 回复的那样,这个问题的答案如下

const query = { clientID: call.args[0] }; 
const update = { $set: { activated: true } }; // Return updated document 
const options = { new: true }; 
call.client.botLoginData.findOneAndUpdate(query, update, options, (err, doc) => { all.message.channel.send('I have successfully updated that bot. Please allow up to 10 mins to propagate, and then restart the bot.'); });

如果有人有任何其他建议,请告诉我! 谢谢您的帮助! :)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-07-27
    • 2018-06-11
    • 1970-01-01
    • 2019-02-20
    • 1970-01-01
    • 2021-08-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多