Reputation: 51
I was trying to pull only one element from an Array which is a mongo document.
My db looks like this:
product: ['foo','foo','foo'],
...
I want to remove only one element from this array.
My db should Look like this:
product: ['foo','foo'],
...
When I was using model.findByIdAndUpdate( id, { $pull: {product: 'foo'} } )
I loose all my values from product
Upvotes: 0
Views: 558
Reputation: 46
`
doc.findById(productId)
.then(async (result) => {
if (!result) {
console.log("No Record Found.");
} else {
result.index = undefined;
await result.save();
console.log('Record Updated Successfully.');
}
})
.catrch(err => {
console.log('Error: ', err);
});
`
You can do this to bring the document and then make the required element as undefined and then you can save the modified document back to the database.
Else you can have a better and optimized approach.
`db.doc.update( { _id: 1 }, { $pop: { products: -1 } } )`
Here the first element from the product array will be deleted.
Note: this is the MongoDB shell syntax.
Upvotes: 2