【问题标题】:How I can use upsert, $inc, $set in sails?我如何在风帆中使用 upsert、$inc、$set?
【发布时间】:2014-01-20 15:47:52
【问题描述】:

如何使用sails-mongo 适配器在sails.js 中使用mongodb 操作,例如“$inc, $set, upsert...”?

我试过这段代码,但适配器无法识别选项。

Word.update(
  {coincidence: 'aaaaa'},
  {amount: 222},
  {upsert:true,safe:true},
  function(err,data){
    if (err){
      console.log(err);
    } else {
      console.log("score succeded");
    }
  }
);

【问题讨论】:

  • 我在末尾添加了一个缺少的右括号。

标签: node.js mongodb sails.js


【解决方案1】:

您必须使用模型的native 方法来执行此操作。它返回本机 Mongo 驱动程序集合的一个实例:

Word.native(function(err, collection) {
  collection.update(
     {coincidence: 'aaaaa'},
     {amount: 222},
     {upsert:true,safe:true},
     function(err){
       if (err){
        console.log(err);
       } else {
        console.log("score succeded");
       }
     }
  );
});

有关 Mongo 本机驱动程序的文档,请参阅 here,其中将向您展示您可以对 native 方法返回的集合执行哪些操作。

【讨论】:

  • 使用native方法时,是否触发了模型的hook?
  • 如果你的意思是像.beforeCreate.afterUpdate这样的生命周期回调,那么答案是否定的。不过,您总是可以自己打电话;它们只是和其他任何方法一样的类方法(例如Word.beforeCreate(values, callback)
猜你喜欢
  • 2018-07-22
  • 1970-01-01
  • 1970-01-01
  • 2014-03-31
  • 1970-01-01
  • 1970-01-01
  • 2016-07-27
  • 2016-08-02
  • 2015-11-18
相关资源
最近更新 更多