【问题标题】:possible to update a property after new model is created in sailsjs?在sailsjs中创建新模型后可以更新属性吗?
【发布时间】:2019-08-09 19:35:11
【问题描述】:

我正在尝试为模型创建新记录,并且在创建模型后我需要稍后保存一些字段。

我有这样的代码

let new_model = await Model.create({ name, type}).fetch();
new_model.content = 'abc';
new_model.save();
TypeError: new_model.save is not a function

我用谷歌搜索过,sailsjs 似乎不能以这种方式完成,所以我想我必须通过风帆使用 updateupdateOne。但问题是,name,type 字段不是唯一的,因此使用update 实际上不会变成所有记录的更新。 updateOne 会给我一个错误,说有不止一个记录

有人对这里可以做什么有任何建议吗?

【问题讨论】:

  • 。如果您的记录具有唯一标识符,则获取。如果没有,那就奇怪了。但如果没有。您可以使用字段数据的组合来提出一些独特的请求。就像名称一样,类型本身可能不是唯一的,而是组合起来是唯一的。
  • @Glen new row 总是有它自己的默认唯一标识符 id 虽然有点奇怪 .fetch 不起作用。我想您的建议与下面的@Dora 答案几乎相同?
  • 那么创建之后new_model里面什么都没有了?我希望 fetch 创建的记录是传回 new_model 的。
  • @Glen new_model 确实取回了记录。我可以console.log(new_model.content)new_model.name 我可以看到namenew_model.save() 给了我一个错误,例如save is not a function。我尝试了很多不同的方法,但都没有奏效。也尝试不使用fetch()
  • 但新型号只是记录。 .save() 不是该记录的函数。然后您需要更新记录,您可以按照 Dora 的描述调用 Model.update。

标签: database save sails.js insert-update


【解决方案1】:

我能想到的另一个选择是使用updateOne 做类似的事情

let new_model = await Model.create({ name, type}).fetch();
// getting your content here or do something else
const content = 'abc';
new_model = await Model.updateOne({ id:new_model.id}).set({content});

【讨论】:

    猜你喜欢
    • 2017-12-13
    • 2015-07-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-04
    • 2019-02-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多