user3409889
user3409889

Reputation: 197

Mongoose: How do I query for a document, create one if not found, but do not update if one is found?

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

Answers (1)

JohnnyHK
JohnnyHK

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

Related Questions