I want to update the data with in existing document and not create a other json document in the database. But its not modifing log is showing { n: 0, nModified: 0, ok: 1 }..please help me thanks in advance
this is my code:
const userUpdatedPassword = await UserPreferred.updateOne({_id: userPreferredExists._id},
{
$push: {
languages: req.body.languages,
storeType: req.body.storeType,
intrestedIn: req.body.intrestedIn
}})
}
i'm passing this data in postman:
{
"languages":["korean,"Hindi"],
"storeType":["gas station"],
"intrestedIn":["sarees"]
}
I've a json document in my db.
{
"_id" : ObjectId("60e968581871a42ab43a2345"),
"languages" : [
"English"
],
"intrestedIn" : [
"clothing",
"foot wear",
"watches",
],
"storeType" : [
"department stores",
"Medical stores"
]
}
I want in this fromat:-
{
"_id" : ObjectId("60e968581871a42ab43a2345"),
"languages" : [
"English",
"korean,
"Hindi"
],
"intrestedIn" : [
"clothing",
"foot wear",
"watches",
"sarees"
],
"storeType" : [
"department stores",
"Medical stores",
"gas station"
]
}
You can use following query as your requirment, i have tried and tested at my local , One thing you have forgot to use closing quote language array for korean
const userUpdatedPassword = await UserPreferred.updateOne({_id: userPreferredExists._id},
{
$push: {
languages: {
$each: req.body.languages
},
storeType: {
$each: req.body.storeType
},
intrestedIn: {
$each: req.body.intrestedIn
}
}
})
But this code will write duplicates in the array, so if you don't want to push duplicates in the array you can use $addToSet in place of $push, like following
const userUpdatedPassword = await UserPreferred.updateOne({_id: userPreferredExists._id},
{
$addToSet: {
languages: {
$each: req.body.languages
},
storeType: {
$each: req.body.storeType
},
intrestedIn: {
$each: req.body.intrestedIn
}
}
})