skip to Main Content

i try to save data using bot command, but everytime i submit the data it will make new object, i want to make it only 1 object but everytime the same user submit data, it will automtically got changes/update, not create new object.

This is how i save the data

const subregis = "!reg ign:";
client.on("message", msg => {
  if (msg.content.includes(subregis)){ 
      const user = new User({
        _id: mongoose.Types.ObjectId(),
        userID: msg.author.id,
        nickname: msg.content.substring(msg.content.indexOf(":") + 1) // so basically anything after the : will be the username
      });
      user.save().then(result => console.log(result)).catch(err => console.log(err));
      msg.reply("Data has been submitted successfully") 
  }
});

This is my schema

const mongoose = require('mongoose');

const Schema = mongoose.Schema;
const profileSchema = new Schema({
    _id: mongoose.Schema.Types.ObjectId,
    userID: String,
    nickname: String,
});

module.exports = mongoose.model("User", profileSchema);

everytime i do command !reg ign it will add new object, not save/update the exiting user id.

2

Answers


  1. If you want to update an existing User you should use the findOneAndUpdate function:

    const subregis = '!reg ign:';
    client.on('message', async (msg) => {
      try {
        if (msg.content.includes(subregis)) {
          const updatedUser = await User.findOneAndUpdate(
            { userID: msg.author.id },
            {
              nickname: msg.content.substring(msg.content.indexOf(':') + 1), // so basically anything after the : will be the username
            },
            {
              new: true, // Return an updated instance of the User
            }
          );
          console.log(updatedUser);
          msg.reply('Data has been submitted successfully');
        }
      } catch (err) {
        console.log(err);
      }
    });
    
    Login or Signup to reply.
  2. The only thing you need to do is check if there is data related to that user before creating a collection.

    Schema.findOne({ userID: msg.author.id }, async (err, data) =>{
       if (data) {
           return msg.reply({content: `you already have a nickname, it's ${data.nicknamd}})
       }
       if (!data) {
           // Create the Schema
       }
    })
    

    If you want to update the nickname use

    const newdata = Schema.findOneandUpdate({}) ...
    //then follow what lpizzini said above
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search