Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

172
Vistas
Updating a Subdocument in MongoDB

I am trying to create a database for my Giveaway Bot. It consist of 2 collections, Main (holding settings) and Giveaway which is nested in under the Main collection. I can create my giveaway's without problems. However I want to add some data later on using findOneAndUpdate.

Running the code below I always get this error: Updating the path 'giveaways.duration' would create a conflict at 'giveaways'. Can anyone help solving this issue ?

schema.js

const giveawaySchema = new mongoose.Schema({  
    _id: String,
    destination: String,
    duration: String,
    winners: String,
    price: String,
})

const mainSchema = new mongoose.Schema({
    _id: String,
    log_channel_id: String,
    admin_roles: [],
    giveaways: [giveawaySchema],

const Main = mongoose.model("mainSchema", mainSchema);
const Giveaway = mongoose.model("giveawaySchema", giveawaySchema);

module.exports = { Main, Giveaway }
});

Part of my code used for updating:

const mongoose = require("mongoose")
const {Main, Giveaway} = require("../models/schema.js")

const newestGiveaway = await Main.findOneAndUpdate(
    {
        _id: guildId,
        'giveaways._id': giveaway_id,
    },  
    {   
        "$set":{
            "giveaways.duration": "3d",
            "giveaways.winners": "20",
            "giveaways.price": "Price to Win",
         },
    },
    {
        upsert: true,
    }
        

Thank you for your help :)

A small side question. I have fetched the Main document (the parent) before already can I make my search cheaper/ more efficent by only searching through this instead of running the findOneandUpdate method on the whole database ?

Edit 1 I found that it is neccesary to use the $ operator and have updated my code. However I still get the same error:

{
   $set:{
      "giveaways.$.duration": durationInput,
      "giveaways.$.winners": winnerAmountInput,
      "giveaways.$.price": priceInput,
   },
},
about 4 years ago · Juan Pablo Isaza
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda