模型仅在Sails中的嵌套模型中显示ID

时间:2016-10-27 02:02:38

标签: javascript sails.js waterline

所以我正在使用sails js开发一个应用程序。我想发一个帖子以及它的评论作为回应。

这是我的模特

Thread.js

module.exports = {

  attributes: {
    id: {
      type: "integer",
      primaryKey: true,
      autoIncrement: true
    },
    title: "string",
    content: "string",
    userId: {
      model: "user"
    },
    createdAt: "string",
    isSecret: "boolean",
    comments: {
      collection: "comment",
      via: "threadId"
    }
  }
};

Comment.js

module.exports = {

  attributes: {
    id: {
      type: "integer",
      primaryKey: true,
      autoIncrement: true
    },
    threadId: {
      model: "thread"
    },
    content: "string",
    createdAt: "string",
    isSecret: "boolean",
    userId: {
      model: "user"
    }
  }
};

在评论中有两个嵌套模型,User和Thread。但响应仅显示id

 {
  "comments": [
    {
      "threadId": 4,
      "content": "Comment of thread one.",
      "createdAt": "10-27-2016 09:39:50",
      "isSecret": false,
      "userId": 5,
      "updatedAt": "2016-10-27T01:50:19.968Z",
      "id": 3
    }
  ],
  "userId": {
    "firstName": "Tio",
    "LastName": "Ammar",
    "email": "adityaamirullah@gmail.com",
    "userName": "tioammar",
    "avatar": "https://tioammar.com/avatar.jpg",
    "createdAt": "2016-10-27T01:33:02.076Z",
    "updatedAt": "2016-10-27T01:33:02.076Z",
    "id": 5
  },
  "title": "Initial Thread",
  "content": "Content of initial thread.",
  "createdAt": "10-27-2016 09:34:50",
  "isSecret": false,
  "updatedAt": "2016-10-27T01:35:29.559Z",
  "id": 4
}

我想展示实际的用户模型。请提前帮助和感谢! :)

1 个答案:

答案 0 :(得分:2)

我认为你要找的是深度/嵌套人口Here is a similar question

可悲的是,Waterline不支持深度人口,如果你想继续使用Waterline,那么你必须做几个查询来实现这一目标。其中一个额外的查询可能看起来像......

Comment.find({threadId: thread.id})
  .populate("userId")
  .exec(function(err, comments){
    if(err)...
    thread.comments = comments;
  });

如果您决定这样做,您可能会这样做 issues using toJSON()