我有一个函数可以根据它的地理坐标查找资源,但是findOne方法不会从模型中返回评论集合。如果我使用蓝图路线根据ID查找,我会随之得到评论。
查找:id JSON
{
"comments": [
{
"text": "Some Text",
"nomination": "551865064a5ccf41274be682",
"createdAt": "2015-03-29T21:02:10.586Z",
"updatedAt": "2015-03-29T21:02:10.586Z",
"id": "55186852d21850a627292db3"
}
],
"name": "Karma Bird House",
"address": "47 Maple Street Burlington, VT 05401",
"geo": "44.473231,-73.217882",
"lat": 44.473231,
"lon": -73.217882,
"streetImg": "http://maps.googleapis.com/maps/api/streetview?size=800x300&location=44.473231,-73.217882",
"votes": 1,
"createdAt": "2015-03-29T20:48:06.109Z",
"updatedAt": "2015-03-29T21:02:48.817Z",
"id": "551865064a5ccf41274be682"
}
findGeo:id JSON
{
"nom": {
"name": "Karma Bird House",
"address": "47 Maple Street Burlington, VT 05401",
"geo": "44.473231,-73.217882",
"lat": 44.473231,
"lon": -73.217882,
"streetImg": "http://maps.googleapis.com/maps/api/streetview?size=800x300&location=44.473231,-73.217882",
"votes": 1,
"createdAt": "2015-03-29T20:48:06.109Z",
"updatedAt": "2015-03-29T21:02:48.817Z",
"id": "551865064a5ccf41274be682"
}
}
findGeo方法
findGeo: function (req, res, next) {
Nomination.findOne({geo: req.param('id')}, function foundNomination(err, nom) {
if(err) return next(err);
if(!nom) return next();
return res.json({
nom: nom
});
})
}
型号:
module.exports = {
attributes: {
id:{
type:"int",
primaryKey: true,
autoIncrement: true
},
// Location's name
name: {
type: 'string',
required: true
},
// Locations Lat and lon
lat: 'float',
lon: 'float',
// lat,lon
geo: {
type: 'string',
unique: true
},
// Location's Address
address: {
type: 'string',
required: true
},
// Number of Votes
votes: {
type: 'integer',
defaultsTo: '0'
},
// Street View Image
streetImg: 'string',
// Association of comments
comments: {
collection: 'comment',
via: 'nomination'
}
}
};
答案 0 :(得分:2)
您需要使用“populate”方法,如下所示:
findGeo: function (req, res, next) {
Nomination
.findOne({geo: req.param('id')})
.populate('comments')
.exec(function (nom) {
if(!nom) return next();
return res.json({
nom: nom
});
});
}