[英]Querying mongoose to perform a join
I have 2 collections setup as below, Dates
and Streets
. 我有2个集合设置,如下所示:
Dates
和Streets
。
What I would like to achieve is to, query Streets by a param StreetName
and look that up to find it's unique ID and then query the other collection by that ID to pull back all the dates that match. 我要实现的是,通过
StreetName
参数查询Streets,并查找其唯一ID,然后通过该ID查询其他集合,以拉回所有匹配的日期。
My route is set up to /wasteDate/:StreetName
. 我的路线设置为
/wasteDate/:StreetName
。 Here's what I have: 这是我所拥有的:
model.js model.js
var DateSchema = new Schema({
date: {
type: Date
},
street_id: {
type: String,
}
});
var StreetSchema = new Schema({
name: {
type: String
}
});
routes.js routes.js
module.exports = function(app) {
var wasteCollections = require('../controllers/wasteController');
app.route('/wasteDate/:streetName')
.get(wasteCollections.get_dates_by_street_name);
};
controller.js controller.js
var mongoose = require('mongoose'),
ColDate = mongoose.model('Dates'),
that = this,
Street = mongoose.model('Streets');
(...) (...)
exports.manual_get_dates_by_street = function (id) {
var wasteDates = ColDate.find({ street_id: id }).lean();
return wasteDates;
};
exports.get_dates_by_street_name = function (req, res) {
Street.find({
name: req.params.streetName
}, function(err, street) {
var query;
var theStreetId = street[0].id;
if (err) res.send(err);
query = that.manual_get_dates_by_street(theStreetId);
res.json(query);
});
};
at the moment i'm getting a circular reference error on the JSON. 目前,我在JSON上收到循环引用错误。
I don't think I'm doing it the right way and think I may need to amend my schema? 我认为我做的方式不正确,认为我可能需要修改自己的架构?
Any help appreciated 任何帮助表示赞赏
I never used it but I think mongoose-models may resolve your problem. 我从未使用过它,但我认为猫鼬模型可以解决您的问题。 https://github.com/SportZing/mongoose-models
https://github.com/SportZing/mongoose-models
Another possible approach is to put the second query function as a callback of the first. 另一种可能的方法是将第二个查询函数作为第一个的回调。
You can either use (1) find
twice or (2) aggregation
. 您可以使用(1)
find
两次或(2) aggregation
。
Here's the first way: 这是第一种方式:
exports.manual_get_dates_by_street = function (id, callback) {
// you are dealing with asynchronous operations, so you have to wait for the callback
// to execute before you can get the data
ColDate.find({ street_id: id }).lean().exec(callback);
};
exports.get_dates_by_street_name = function (req, res) {
// you are expecting one result, so use findOne instead of find
Street.findOne({ name: req.params.streetName }, function (err, street) {
// make sure you handle errors properly such as stopping execution of
// the next lines or else you may get unexpected errors
if (err)
return res.send(err);
// we pass a callback that will be executed once results (or an error) are found
that.manual_get_dates_by_street(street._id, function (err, dates) {
res.json({ dates: dates });
});
});
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.