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

177
Views
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
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!