-1

So I am trying to make a level system with Node.JS, Discord.js, and MongoDB, but I can't figure out, how to add/update data in the database.

Here is the code I use, but it doesn't work:

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,
 });
}
Lioness100
  • 8,260
  • 6
  • 18
  • 49
  • 1
    What do you mean, "doesn't work"? – Sergio Tulentsev Sep 11 '20 at 14:59
  • @SergioTulentsev, it only updates, but doesn't insert. – Vid Forstner Sep 11 '20 at 15:14
  • Hi, I posted an answer to your question. Be advised that you might be downvoted for your question since it seems an easily googleable question, and is kinda duplicate to other questions : [here for example](https://stackoverflow.com/questions/7267102/how-do-i-update-upsert-a-document-in-mongoose?rq=1). – Chalibou Sep 11 '20 at 15:57

1 Answers1

0

Welcome to stackoverflow,

First of all, db.collection(message.guild.id).findOne({user: message.author.id}) returns a promise, so you have to handle it properly either by using .then() or async/await method, or any third party promise manager if that's your stuff.

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

But you do not even need that for your problem : there is a way of updating an object to a MongoDB or insert it if it does not already exists : use the upsert:true option, 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
   }
)

Your code should look like this :

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