I want to append or push my new items that I input in the array without creating new mongoose schema..what I mean is that I will only push items without creating new _id
...Here is my code..
For mongoose.Schema()
const mainSchema = new Schema({
likes:{
type:Number,
max:100000
},
people:[{
key:{type:String},
name:{type:String}
}]
},{
timestamps:true
})
And for the routes that will post my items..
router.route('/item/1').post((req,res) => {
const { likes, people } = req.body
const FirstItem = Main({
likes,
// people
})
FirstItem.people.push(people)
FirstItem.save()
.then(likes => res.json('New User Added'))
.catch(err => res.status(400).json('Error :' err))
})
As you see I didn't input new Main({})
in my post because I don't wanna create a new _id
..but I want to push my items in my array whenever I create another new items....This is how I write it in postman..
{
"likes":0,
"people":[
{
"key":"Tes22t",
"name":"Tit213an"
}
]
}
Now if I changed something after posting this in my POST method. like "key":"testetsee","name":"123123123"
it will give me an error like this ...
"Error :ValidationError: people.0._id: Cast to ObjectId failed for value \"[ { key: 'Tes22t', name: 'Tit213an' } ]\" (type Array) at path \"_id\""
I think my problem here is pushing the item? or the post? or do I just need to update it?
CodePudding user response:
If you only want push an element into people array of that object, you should use updateOne() instead of save()
So the code will like
router.route('/item/1').post((req,res) => {
const { likes, people } = req.body
const model = mongoose.model('collection_name', mainSchema);
model.updateOne({like}, {$addToSet: { people: {$each: people} }})
.then(likes => res.json('New User Added'))
.catch(err => res.status(400).json('Error :' err))
})