2017-02-04 34 views
0

我的用戶採集模型模式:的NodeJS:創建參照收集場的搜索查詢

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}) 
    }); 

這是我的代碼。我想用地址重複號碼過濾。但我沒有得到正確的結果與此查詢。

回答

0

第一個Mongoose通過{「useraddress.repeat」:{$ gte:val}}查詢來執行對用戶集合的搜索。並且只有在通話開始之後。

所以你應該得到0結果,因爲地址尚未填充。

這裏有2種解決方法。首先,檢查出this answer請。 你需要:

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

 
\t \t //Do needed stuff here. 
 
\t });

第二種方法是使用聚集和$查找(你需要的MongoDB v 3.2+)。基本上它意味着將這個人口和過濾移到數據庫級別。

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