Home > Software design >  Mongoose - using findByIdAndUpdate - pushing an object into array pushes automatically id also in. W
Mongoose - using findByIdAndUpdate - pushing an object into array pushes automatically id also in. W

Time:08-18

When I update a document and push an object to an array (here below I push a new object containing info and date into the report array), an id is always being added and pushed into it. Why is that? Whats wrong in my code?

I create:

report: {
info: 'abc',
date:...,
_id: "'123'
}

but its suppose to be just:

report: {
info: 'abc',
date:...
}
const productSchema = new mongoose.Schema({
    name: { 
        type: String,
        required: true
    },
    hasReport: {
        type: Boolean
    },
    // if there is no reports, it will be an empty array, if there is i just push a new object into the array
    report: [{
        info: String,
        date: Date
    }],
}
mongoose.model('Product', productSchema);

updateProduct: async (req, res) => {
    const { id, hasReport, report: {info}} = req.body;
    const station = await Product.findByIdAndUpdate({_id: id}, {
           $push: {
               report: {
                   info: info,
                   date: new Date()
               },
           }, $set: {hasReport: true}})
    product.save()
}

CodePudding user response:

Try to create report schema as:-

cont reportSchema = new mongoose.Schema({
        info: String,
        date: Date
    }, { _id: false })

const productSchema = new mongoose.Schema({
    name: { 
        type: String,
        required: true
    },
    hasReport: {
        type: Boolean
    },
    report: [reportSchema],
}
mongoose.model('Product', productSchema);

it should work for you.

CodePudding user response:

Object inside array is also considered as doc in MongoDB. So, it will auto create id for each. If you want to disable this behaviour for objects of array then you can do it from your schema file.

cont reportSchema = new mongoose.Schema({
     info: String,
     date: Date
}, { _id: false })
  • Related