Reputation: 1076
I try to update an MongoDB data by using this code:
db.medicines.update({"_id":"586a048e34e5c12614a7424a"}, {$set: {amount:'3'}})
but unfortantly the query does not recognize the selector "_id":"586a048e34e5c12614a7424a"
, even if its exists.
Its succsed when I change the key to another like: name
,rate
and etc..
there is a special way to use update with _id
parameter?
Thanks a head.
Upvotes: 0
Views: 37
Reputation: 11786
_id
will be the unique ObjectId
that mongodb generates for every document before inserting it. The query dint work because _id
is an ObjectId
and "586a048e34e5c12614a7424a"
is a String
. You need to wrap _id
with ObjectId()
.
If you're using mongodb query
db.medicines.update({
"_id": ObjectId("586a048e34e5c12614a7424a")
}, {
$set: {
amount: '3'
}
});
If you are using mongoose
. You can use findByIdAndUpdate
db.medicines.findByIdAndUpdate({
"_id": "586a048e34e5c12614a7424a"
}, {
$set: {
amount: '3'
}
});
Upvotes: 2