如何让 toJSON 在 Sails.js 中返回对象之前等待查找

How to make toJSON wait for find before returning the object in Sails.js?

本文关键字:对象 返回 查找 等待 js toJSON Sails      更新时间:2023-09-26

>我在模型中的以下 toJSON 中运行查找,但它在查找完成之前返回对象。如何等到查找完成再触发退货?

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 :(
}

目标是让obj.comments在返回时处于obj状态。

解决方案最终是在帖子和评论之间添加关联。

您可以在此处找到有关此的文档:http://sailsjs.org/#/documentation/concepts/ORM/Associations

例如,在后期模型中添加如下属性

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

并在注释模型中添加此属性

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

添加新文档时,将评论的 postId 设置为要关联的帖子的 ID。然后在帖子控制器中查找帖子时

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