gusya59
gusya59

Reputation: 45

findOneAndUpdate the latest document

This is my schema

 var BudgetSchema = mongoose.Schema({
  user_email: { type: String, required: true },
  user_budget: { type: Number, required: true },
  platforms_budget: {
    type: [{
      platform_id: { type: String, required: true },
      platform_name: { type: String, required: true },
      platform_budget_percent: { type: Number, required: true },
      platform_budget: { type: Number, required: true },
    }]
  },
  created: { type: Date, default: Date.now() }
});

var BudgetSchemaExport = module.exports = mongoose.model('Budget', BudgetSchema);

And this is the function:

module.exports.updateBudgetPercent = async function (user_email, platform_name, p_budget) {
  var query = {
    "user_email": user_email,
    "platforms_budget": {
      $elemMatch: { "platform_name": platform_name }
    }
  };
  //the location that need to be updated
  var update = { "$set": { "platforms_budget.$[outer].platform_budget_percent": p_budget }  };
  //array's index
  var options = { arrayFilters: [{ "outer.platform_name": platform_name }] };
  var updated = await this.findOneAndUpdate(query, update, options).sort({ created: -1 })
  if (updated) { //if the data was updated
    return true;
  } else {
    return false;
  }
}

The purpose of the function is to update a budget for specific user. I want to update the latest document, but it updates the earliest/first one.

I tried this option: var updated = await this.findOneAndUpdate(query, update, options, {sort:{ "created": -1 }}), but I got an error:

events.js:167
      throw er; // Unhandled 'error' event
      ^
TypeError: callback.apply is not a function

Any ideas? Thanks.

Upvotes: 0

Views: 1631

Answers (1)

Chaitanya
Chaitanya

Reputation: 237

Use upsert: true with sort: { created: -1 }. Here is the query:

var updated = await this.findOneAndUpdate(
  query,
  update,
  {
    upsert: true,
    sort: { created: -1 },
  }
);

Hope this helps you.

Upvotes: 7

Related Questions