从两个集合中填充
我为2个不同的集合定义了2个Schema,我需要将其中的一个填充到另一个:
stationmodel.js
var stationSchema = new Schema({ StationName: 'string', _id: 'number', Tripcount: [{ type: Schema.Types.ObjectId, ref: 'Tripcount'}] }, {collection: 'stations'} ); module.exports = mongoose.model('Station', stationSchema);
tripmodel.js
var tripSchema = new Schema({ _id: { type: Number, ref: 'Station'}, Tripcount: 'number' }, {collection: 'trips'} ); module.exports = mongoose.model('Tripcount', tripSchema);
根据mongoose填充文件 ,这是要走的路。 当我使用邮递员获取电台时,我遇到“Tripcount”仍然是[]
的问题。
我的“电台”collections的数据库结构:
{ "_id": 1, "StationName": "Station A", }
而对于“旅行”集合:
{ "_id": 1, "Tripcount": 6 }
我的routes.js:
module.exports = function(app) { app.get('/stations', function(req,res) { var query = Station.find().populate('Tripcount'); query.exec(function(err, stations){ if(err) res.send(err); res.json(stations); }); }); };
我似乎无法find错误,也许有人在这里可以发现我犯的一个错误。
您在单引号中包含了mongoose SchemaTypes ,您需要在文档中定义属性时直接引用SchemaTypes ,该属性将转换为其关联的SchemaType 。
例如,当您在Tripcount
中定义Tripcount
时, tripSchema
其转换为Number
SchemaType as
var tripSchema = new Schema({ _id: Number, Tripcount: Number }, {collection: 'trips'}); module.exports = mongoose.model('Tripcount', tripSchema);
和车站架构
var stationSchema = new Schema({ _id: Number, StationName: String, Tripcount: [{ type: Number, ref: 'Tripcount'}] }, {collection: 'stations'}); module.exports = mongoose.model('Station', stationSchema);
然后在您的stations
collections中,文档理想地将具有结构
{ "_id": 1, "StationName": "Station A", "Tripcount": [1] }
为填充方法的工作,其中应用为
Station.find().populate('Tripcount').exec(function(err, docs){ if (err) throw err; console.log(docs); // prints { "_id": 1, "StationName": "Station A", "Tripcount": [{"_id": 1, Tripcount: 6 }] } });
替代方法
如果站点集合没有Tripcount
字段,则可采用另一种方法是使用在汇总框架中find的$lookup
运算符:
Station.aggregate([ { "$lookup": { "from": "tripcollection", "localField": "_id", "foreignField": "_id", "as": "trips" } }, { "$project": { "StationName": 1, "trips": { "$arrayElemAt": ["$trips", 0] } } }, { "$project": { "StationName": 1, "Tripcount": "$trips.Tripcount" } } ]).exec(function(err, docs){ if (err) throw err; console.log(docs); // prints [{ "_id": 1, "StationName": "Station A", "Tripcount": 6 }] } });