【问题标题】:get record `id` before create/save | Sails Js在创建/保存之前获取记录`id` |帆 Js
【发布时间】:2017-02-20 13:40:27
【问题描述】:

我正在尝试为用户创建通知。

在像这样http://localhost:1337/invited/accept?referrer=msgIcon&id=this-notification-id这样的描述中带有通知url,该url具有这个新创建的通知的id。

  AppUserNotification.create({
    projectId: projectId,
    appuser: appusers.id,
    notificationTitle: 'You are invited in project',
    isRead: 0,
    description: 'You are invited in project collaboration, '
    + 'please accept invitation by following the link.\nHave a good day !\n'
    + 'Accept Invitation http://localhost:1337/invited/accept?referrer=msgIcon&id=this-notification-id',
  }).exec(function (err, appuserNotifications) {
    apiStatus = 1; // heading toward success
    if (err){
      return false;
    }else if(appuserNotifications){
      return true;
    }
  });//</after AppUserNotification.create()>

我想要做的是用这个新创建的通知在描述中保存一个链接。但无法做到这一点。 请帮帮我。

【问题讨论】:

  • 你不能那样做。 Id 来自数据库,因此只能在回调中访问。您可以在创建后更新它。 appuserNotifications.description = 'your desc with id'; appuserNotifications.save()

标签: javascript node.js mongodb sails.js


【解决方案1】:

默认id由数据库在创建记录时生成。所以创建后才能访问。

以下是实现目标的一些方法:

  1. 新属性:添加另一个用于描述 URL 的唯一属性。可以在创建前随机生成(例如可以使用UUID
  2. 使用自定义id:在Model中设置autoPK: false,自己生成id; (我已经在beforeCreate 钩子中使用UUID 作为主键id 为MySQL 完成了它,不确定MongoDB)
  3. 创建后更新:使用afterCreate钩子更新描述id
  4. 新模型方法:在模型中定义一个方法getDescription(),它返回类似this.description + this.id的内容。
  5. 覆盖toJSON()http://sailsjs.com/documentation/reference/waterline-orm/records/to-json

【讨论】:

  • 这很有帮助,但寻找描述在创建时获取 ID 的示例
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-07-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多