Javascript 如何让toJSON在返回Sails.js中的对象之前等待查找?
我在模型中的以下toJSON中运行查找,但它在查找完成之前返回对象。我怎样才能等到查找完成后再触发返回Javascript 如何让toJSON在返回Sails.js中的对象之前等待查找?,javascript,node.js,express,sails.js,Javascript,Node.js,Express,Sails.js,我在模型中的以下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 refl
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
中。解决方案是在帖子和评论之间添加一个关联
您可以在此处找到关于此的文档:
例如,在post模型中添加如下属性
comments: {
collection: 'comment',
via: 'postID'
},
.populate('comments', {
limit: 3,
sort: 'createdAt DESC'
}).exec(...
并在comments模型中添加此属性
postId: {
model: 'hacks',
type: 'STRING',
required: true
},
添加新文档时,将评论的posted设置为要关联的帖子的id。
然后在post控制器中查找post时添加如下填充
comments: {
collection: 'comment',
via: 'postID'
},
.populate('comments', {
limit: 3,
sort: 'createdAt DESC'
}).exec(...