【问题标题】:Writing data to a Mongodb or updating it, if it's already in the database将数据写入 Mongodb 或更新它,如果它已经在数据库中
【发布时间】:2020-12-30 02:56:36
【问题描述】:

所以我正在尝试使用 Node.JS、Discord.js 和 MongoDB 制作一个关卡系统,但我不知道如何在数据库中添加/更新数据。

这是我使用的代码,但它不起作用:

if (db.collection(message.guild.id).findOne({ user: message.author.id })) {
 db.collection(message.guild.id).updateOne(
  { user: message.author.id },
  {
   $set: { lastmessage: Date.now() },
  }
 );
} else {
 db.collection(message.guild.id).insertOne({
  user: message.author.id,
  lastmessage: Date.now(),
  level: 0,
  xp: 0,
 });
}

【问题讨论】:

  • “不起作用”是什么意思?
  • @SergioTulentsev,它只更新,但不插入。
  • 您好,我发布了您问题的答案。请注意,您的问题可能会被否决,因为这似乎是一个易于搜索的问题,并且与其他问题有点重复:here for example.

标签: javascript node.js mongodb discord.js


【解决方案1】:

欢迎来到stackoverflow,

首先,db.collection(message.guild.id).findOne({user: message.author.id}) 返回一个承诺,因此您必须使用.then()async/await 方法或任何第三方承诺管理器(如果这是您的东西)正确处理它。

db.collection(message.guild.id).findOne({user: message.author.id}).then((result)=>{
    //Do stuff with result
})

但你甚至不需要它来解决你的问题:有一种方法可以将对象更新到 MongoDB 或在它不存在时插入它:使用 upsert:true 选项,see documentation

db.collection.updateOne(
   <filter>,
   <update>,
   {
     upsert: <boolean>,
     writeConcern: <document>,
     collation: <document>,
     arrayFilters: [ <filterdocument1>, ... ],
     hint:  <document|string>        // Available starting in MongoDB 4.2.1
   }
)

您的代码应如下所示:

db.collection(message.guild.id).updateOne(
     {user: message.author.id},
     {$set: { lastmessage: Date.now()}},
     {upsert:true}
);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-11-11
    • 1970-01-01
    • 2017-06-04
    • 1970-01-01
    • 1970-01-01
    • 2020-04-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多