0

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?

NVO
  • 2,566
  • 5
  • 27
  • 57
  • 1
    Basically it's "by design", both in that `_id` is there because it actually is good practice to have it, but you can turn it off. Also "defaults" are specified in your schema, so mongoose uses them. And again, you can turn this off per operation if you must. Or of course just don't specify a schema with defaults unless you always want them. – Neil Lunn Nov 14 '18 at 10:38
  • Please read my question, it's not about the _id field. – NVO Nov 14 '18 at 10:39
  • 2
    I can read. Please take more than one minute to read the answers and understand them. – Neil Lunn Nov 14 '18 at 10:41
  • Didn't see the second question, but now I see. I did make some changes but that's not solving this. I will update my question. – NVO Nov 14 '18 at 11:04

0 Answers0