Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

168
Views
¿Cómo guardar datos sin crear un nuevo objeto en la base de datos mongoose?

Intento guardar datos usando el comando bot, pero cada vez que envío los datos creará un nuevo objeto, quiero que sea solo 1 objeto, pero cada vez que el mismo usuario envíe datos, obtendrá cambios/actualizaciones automáticamente, no creará un nuevo objeto.

Así guardo los datos

 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") } });

este es mi esquema

 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);

cada vez que ordeno !reg ign , agregará un nuevo objeto, no guardará/actualizará la identificación del usuario existente.

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Si desea actualizar un User existente, debe usar la función findOneAndUpdate :

 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); } });
about 4 years ago · Juan Pablo Isaza Report

0

Lo único que debe hacer es verificar si hay datos relacionados con ese usuario antes de crear una colección.

 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 } })

Si desea actualizar el uso de apodo

 const newdata = Schema.findOneandUpdate({}) ... //then follow what lpizzini said above
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!