【问题标题】:Why is Model.save() not working in Sails.js?为什么 Model.save() 在 Sails.js 中不起作用?
【发布时间】:2014-11-26 08:30:02
【问题描述】:

Save() 给我错误,例如“对象没有方法 'save'”

Country.update({id:req.param('country_id')},model).exec(function(err,cntry){ if(err) 返回 res.json(err); 如果(!cntry.image){ cntry.image = '图片/国家/'+文件名; cntry.save(function(err){ console.log(err)}); } })

关于如何在更新查询中保存模型的任何想法。 ??

【问题讨论】:

  • 您使用的是 Waterline 和sails-mongo,还是Mongoose?在我看来像水线。

标签: node.js mongoose sails.js sails-mongo


【解决方案1】:

当使用 mongoose (3.8) 直接更新数据库时,回调函数接收 3 个参数,此时都不是定义模型的 mongoose 对象。参数为:

  • err 是发生错误时的错误
  • numberAffected 是 Mongo 报告的更新文档的计数
  • rawResponse 是来自 Mongo 的完整响应

正确的做法是,先获取数据,再更改数据:

Country.findOne({id: req.param('country_id')}, function (err, country) {
  // do changes
})

或者使用更新方法,你想要的方式:

Country.update({id: req.param('country_id'), image: {$exists: false}}, {image: newValue}, callback) 

【讨论】:

    【解决方案2】:

    假设您使用的是 Waterline 和sails-mongo,这里的问题是update 返回一个数组(因为您可以一次更新多条记录),并且您将其视为一条记录。试试:

    Country.update({id:req.param('country_id')},model).exec(function(err,cntry){
    
             if(err) return res.json(err);
    
             if(cntry.length === 0) {return res.notFound();}
    
             if(!cntry[0].image){
    
                   cntry[0].image = 'images/countries/'+filename;
                   cntry[0].save(function(err){ console.log(err)});
             }
    });
    

    不过,在我看来,这是一段奇怪的代码;为什么不在model 中检查image 的存在,然后再执行Country.update 并相应地更改model(或其副本)?这将为您节省额外的数据库调用。

    【讨论】:

      猜你喜欢
      • 2011-07-24
      • 2011-05-25
      • 2015-09-18
      • 1970-01-01
      • 1970-01-01
      • 2016-12-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多