findOneAnd更新最新文档

时间:2018-10-01 11:27:19

标签: javascript node.js mongodb mongoose 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);

这是函数:

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;
  }
}

该功能的目的是为特定用户更新预算。 我想更新最新的文档,但是它更新了最早的/第一个文档。

我尝试了以下选项:var updated = await this.findOneAndUpdate(query, update, options, {sort:{ "created": -1 }}),但出现错误:

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

有什么想法吗?谢谢。

1 个答案:

答案 0 :(得分:0)

upsert: truesort: { created: -1 }一起使用。这是查询:

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

希望这对您有所帮助。