Nodejs:使用引用集合字段创建搜索查询

时间:2017-02-04 12:03:50

标签: node.js mongodb mongoose

我的用户集合模型架构:

var userModel = new Schema({
    userAddress: { type: Object, ref: 'useraddress' },
    name: String,
});

我的用户地址集合模型架构:

var addressModel = new Schema({
    macAddress: String,
    repeat: Number,
});

获取数据方法是:

module.exports.get = function (req, res) {
var _repeatTime = 2;
var _searchQRY = [];
_searchQRY.push(
    {
        "useraddress.repeat": { $gte: _repeatTime}
    });
userModel.find({ $and: _searchQRY }).populate('useraddress').exec(function (err, results) {
        res.json({ record: results})
    });

这是我的代码。我想用地址重复数过滤。但是我没有通过此查询获得正确的结果。

1 个答案:

答案 0 :(得分:0)

First Mongoose通过{“useraddress.repeat”:{$ gte:val}}查询执行对用户集合的搜索。只有在通话开始后才会出现人口。

所以你应该得到0结果,因为地址尚未填充。

以下是解决此问题的两种方法。首先,请查看this answer。 你需要:

//Any conditions that apply to not populated user collection documents
var userQuery = {};
userModel.find(userQuery)
	//Populate only if the condition is fulfilled
	.populate('useraddress', null, {"useraddress.repeat": { $gte: _repeatTime}})
	.exec(function (err, results) {
		results = results.filter(function(doc){
			//If not populated it will be null, so we filter them out
			return !!doc.useraddress;
		});

		//Do needed stuff here.
	});

第二种方法是使用聚合和$ lookup(你需要mongodb v 3.2+)。基本上它意味着移动此填充并过滤到DB级别。

userModel
	.aggregate()
	//Anything applying to users collection before population
	.match(userQuery)
	.lookup({
		from: 'address', //Please check collection name here
		localField: 'useraddress',
		foreignField: '_id',
		as: 'useraddress'
	})
	//Lookup pushes the mathes to an array, in our case it's 1:1, so we can unwind
	.unwind('useraddress')
	//Filter them as you want
	.match({'useraddress.repeat': { $gte: _repeatTime}})
	.exec(function (result) {
		//Get the result here.
	});