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

307
Views
¿Cómo agregar ObjectId solo si ObjectID no está presente en la matriz en mongodb usando mongoose?

así que tengo un esquema en el que quiero agregar ObjectID a una matriz de ID en mongoose, intenté agregarlo único, pero no funcionó. Probablemente porque necesito iterar para verificar, pero no estoy seguro de cómo hacerlo en mongoose/mongodb. ¿Alguien me puede ayudar?

el esquema se ve así:

 const favoriteSchema = new mongoose.Schema({ user: { type: mongoose.Schema.Types.ObjectId, ref: "User", unique: true, }, favoriteSellers: [ //create array of object id, make sure they are unique for user not to add multiple sellers { type: mongoose.Schema.Types.ObjectId, ref: "Seller", unique: true, }, ], });

y aquí está el código donde intento insertar el ID de objeto solo si no está presente:

 router.put("/favorite", async (req, res) => { const seller_id = mongoose.Types.ObjectId(req.body.seller_id); Favorite.findOne({ user: req.user._id }) .then(async function (result) { if (!result) { return res .status(404) .send({ error: "Could not find your list. Contact support team." }); } result.favoriteSellers.push(seller_id); await result.save(); res.send(result); }) .catch((err) => { res.status(404).send({ error: "Could not add to favorites" }); }); });

Entonces, lo que estoy haciendo es obtener la identificación del usuario y agregar una nueva identificación del vendedor a la matriz, pero quiero agregar una condición si y solo si la identificación del vendedor no está presente en la matriz de vendedores favoritos. También puedo hacer la lógica en el front-end antes de enviar la identificación del vendedor, pero no estoy seguro de si será mejor hacerlo en el back-end y no preocuparme por eso en el front-end. ¡Gracias!

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

Mirando los documentos de Mongoose para agregar subdocs a matrices , creo que debería poder usar addToSet en lugar de push :

 result.favoriteSellers.push(seller_id);

se convierte

 result.favoriteSellers.addToSet(seller_id);
over 4 years ago · Santiago Trujillo 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!