How do I make toJSON wait for a search before returning an object in Sails.js?

I am running a search inside the following toJSON in the model, but it returns an object before the search finishes. How can I wait until a find is complete before starting a refund?

toJSON: function() {
 var obj = this.toObject();
 Comment.find({
    postID: obj.id
 }).limit(2).sort('createdAt DESC').exec(function(err, comments) {
    obj.comments = comments; //this is not reflected in return obj
    if (obj.isTrue) {
        //yes
    } else {
        //no
    }
});
return obj; // obj.comments not reflected :(
}

      

The goal is to obj.comments

be in obj

when he returns.

+3


source to share


1 answer


The solution turned out to be to add an associated relationship between posts and comments.

You can find the documentation here: http://sailsjs.org/#/documentation/concepts/ORM/Associations

For example, in a post model add an attribute like this

comments: {
  collection: 'comment',
  via: 'postID'
},

      



And in the comment model add this attribute

postId: {
  model: 'hacks',
  type: 'STRING',
  required: true
},

      

when adding new documents, set the postId comment to the id of the post you want to link. Then in the post controller, when you find posts, add them so that they

.populate('comments', {
  limit: 3,
  sort: 'createdAt DESC'
}).exec(...

      

0


source







All Articles