0

So i'm developing an app using sails js. I want to send a thread along with it's comments as a response.

here's my model

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"
    }
  }
};

Inside the comment there are two nested model, User and Thread. But the response only shows the 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
}

I would like to show the actual User model. Please help and thanks in advance! :)

user2047836
  • 47
  • 1
  • 6

1 Answers1

2

I think what you are looking for is deep/nested population. Here is a similar question.

Sadly, Waterline doesn't support deep population and if you want to continue to use Waterline, then you would have to do several queries to achieve that. One of the extra queries might look something like...

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

If you decide to do this, you might have issues using toJSON().

Community
  • 1
  • 1
hawkcurry
  • 166
  • 4
  • Deep populate is available in Waterline fork with merged few cool features. It's called Offshore ORM and you can add it to Sails.js with hook: https://github.com/Atlantis-Software/sails-hook-orm-offshore – Bonanza Oct 27 '16 at 09:17