Reputation: 197
My code is this:
X.findOneAndUpdate(
{
'x' : x,
'date' : { $gte : cutOffDate }
},
{ date : Date.now() }, //does not work since it will override existing dates
{ upsert : true }
);
I want to find the most recent X within a time period, if there are no X's found, create one and set the time to now. But if I did find an X, don't update the time. How do I do this?
Setting a default time in the mongoose schema does not work: https://github.com/LearnBoost/mongoose/issues/624
Upvotes: 3
Views: 103
Reputation: 311855
You can use $setOnInsert
to specify the fields you want to set only if an insert is required by the upsert:
X.findOneAndUpdate(
{
'x' : x,
'date' : { $gte : cutOffDate }
},
{ $setOnInsert: { date : Date.now() } },
{ upsert : true }
);
Upvotes: 2