使用以下功能,操作无法正确构建标准。
getArticlesByUser:function(cb,val)
{
Article.find({state:'Normal'}).populate('user', {id: cb.iduser }).populate('images').populate('devise').exec(function(err,article){
if(article)
{
val(null,article);
}
if(err)
{
val(err,null);
}
})
}
似乎忽略了user
模型的标准。
我该如何解决?
答案 0 :(得分:2)
populate方法有两个参数:
如示例in the docs中所示,第二个参数不是必需的,仅在您具有一对多关联时才有用。
例如,如果你有这些模型:
createdAt:
type: datetime
gedmo:
timestampable:
on: create
column: created_at
updatedAt:
type: datetime
gedmo:
timestampable:
on: update
column: updated_at
以下是使用// Article.js
module.exports = {
attributes: {
author: { model: 'user' },
title: { type: 'string' }
}
};
// User.js
module.exports = {
attributes: {
articles: {
collection: 'article',
via: 'author'
},
name: { type: 'string' }
}
};
的一些方法:
populate
在您的情况下,您想要获取用户的文章。这是如何做到的:
// Get a user from his name
User.findOne({ name: 'Pisix' }).function(err, result) {
console.log(result.toJSON());
});
/*
{ name: 'Pisix',
createdAt: Wed Jun 20 2015 14:07:25 GMT-0600 (CST),
updatedAt: Wed Jun 20 2015 14:07:25 GMT-0600 (CST),
id: 7 }
*/
// Get a user from his name + his articles
User.findOne({ name: 'Pisix' }).populate('articles').function(err, result) {
console.log(result.toJSON());
});
/*
{ articles:
[ { title: 'The first article',
id: 1,
createdAt: Wed Jun 20 2015 14:12:33 GMT-0600 (CST)
updatedAt: Wed Jun 20 2015 14:12:33 GMT-0600 (CST) },
{ title: 'Another article',
id: 2,
createdAt: Wed Jun 21 2015 15:04:12 GMT-0600 (CST)
updatedAt: Wed Jun 21 2015 15:04:12 GMT-0600 (CST) },
{ title: 'I\'m back',
id: 10,
createdAt: Wed Jun 30 2015 13:25:45 GMT-0600 (CST)
updatedAt: Wed Jun 30 2015 13:25:45 GMT-0600 (CST) } ],
name: 'Pisix',
createdAt: Wed Jun 20 2015 14:07:25 GMT-0600 (CST),
updatedAt: Wed Jun 20 2015 14:07:25 GMT-0600 (CST),
id: 7 }
*/
// Get a user from his name + one of his articles from its title
User.findOne({ name: 'Pisix' }).populate('articles' , { title: 'The first article' }).function(err, result) {
console.log(result.toJSON());
});
/*
{ articles:
[ { title: 'The first article',
id: 1,
createdAt: Wed Jun 20 2015 14:12:33 GMT-0600 (CST)
updatedAt: Wed Jun 20 2015 14:12:33 GMT-0600 (CST) } ],
name: 'Pisix',
createdAt: Wed Jun 20 2015 14:07:25 GMT-0600 (CST),
updatedAt: Wed Jun 20 2015 14:07:25 GMT-0600 (CST),
id: 7 }
*/