Reputation: 43
I have an object which looks like this:
const prod = {
_id: 123123123,
name: "car",
description: "BMW X6"
}
I use Mongoose to work with Mongo.
I need to find a document with the exactly same _id
and then take a look at its 'description' field. If it has null (or any other falsy value) I need to update document, using 'description' from the object above. If a document already has description, this field remains the same (no update).
How do I do this?
Upvotes: 1
Views: 2566
Reputation: 2359
use pipleline in update like this
db.collection.update({_id:123123123},
[
{
$set: {
description: {
$cond: {
if: {
$or: [
{
$eq: [
false,
"$description"
]
},
{
$eq: [
null,
"$description"
]
},
{
$eq: [
"",
"$description"
]
}
]
},
then: 1,
// overwrite prop value
else: "$description",
// return origin value
}
}
}
}
])
https://mongoplayground.net/p/GHJIYFXhM4V
Upvotes: 1