I have the following collection in MongoDB:
shop: {
products: [{
(...)
_id: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Product',
unique: true
},
dateAdded: {
type: Date,
default: Date.now,
required: true
},
dateModified: {
type: Date,
default: Date.now,
},
}]
}
Which, according to their names, contains the date when the product is created an when he is updated.
I'm updating a product like this:
Shop.findOneAndUpdate({
_id: shopId,
"products._id": prod._id
},
{
"$set": {
"products.$": prod
}
},
{
new: true,
upsert: true
})
'prod' does not contains all the fields of the product, so I use $set to only save the fields which I provide instead of cleaning those.
'prod' does contain an _id field and an dateModified value, but not an dateAdded, but that field is actually updated with the Date.now value, which leads to that dateAdded and dateModified always has the same value.
How can I fix this? dateAdded must only be filled when he is empty, but since I'm updating here, you can assume that there is an value for that field.
Edit for duplicate mark This question is not about the _id field, that is working fine and only added to make this question more clearer. It's about the default value of an different field (dateAdded)
Edit 2
Following the marked questions I changed my query to this:
Shop.update({
_id: shopId,
"products._id": prod._id
},{
"$set": {
"products.$": prod
}
},{
new: true
})
So, I changed the findOneAndUpdate()
to update()
and removed the upsert:true
option, but still the dateCreated is updated with date.now()
. Did I miss something?