Update Database Entry Using Mongoose
Solution 1:
Assuming this is your document structure,
{
"_id" : ObjectId("5f2ae5a4b1549ac0460920dd"),
"projectName" : "A",
"project" : [
{
"companyName" : "T1",
"contactPerson" : {
"work_email" : "t1@gmail.com"
}
},
{
"companyName" : "T2",
"contactPerson" : {
"work_email" : "t2@gmail.com"
}
}
]
}
Single Update updateOne()
If you know email
will be unique and want to update single document then use updateOne()
.
- first is query part to find condition, email
t1@gmail.com
- second is set/update part, here
$
is for array becauseproject
is an array, updatecompanyName
toT1 Company
await ClientManagers.updateOne(
{ 'project.contactPerson.work_email': 't1@gmail.com' },
{
$set: { "project.$.companyName": "T1 Companmy" }
}
)
Multiple Update updateMany()
If email
is not unique and want to update everywhere then use updateMany()
, it will update every matching documents.
await ClientManagers.updateMany(
{ 'project.contactPerson.work_email': 't1@gmail.com' },
{
$set: { "project.$.companyName": "T1 Company" }
}
)
Not suggesting update() method to use, because its deprecated in mongoose and will give Deprecation Warnings , this function is replaced with
updateOne()
,updateMany()
andreplaceOne()
methods.
Solution 2:
Good start. Mongo has better documentation with examples. I suggest you to refer that also.
use update
db.collection.update({companyName:'x bv'}, {"$set":{"companyName":y}})
Mongo is case sensitive. So name should match exactly.
update
updates one document. To update multiple, use updateMany
or multi:true
option with update
or findOneAndMondify
for one update for find and update
case.
Post a Comment for "Update Database Entry Using Mongoose"