2016-04-14 50 views
0

Mongo令我瘋狂。我有這些模式:無法通過Mongo中的點符號搜索子文檔(mongoose)

var userSchema = new Schema({ 
username: { 
    type: String, 
    require: true, 
    unique: true 
}, 
password: { 
    type: String, 
    require: true, 
} 
}); 
var User = mongoose.model('user', userSchema); 

var deviceSchema = new Schema({ 
name: { 
    type: String, 
    require: true, 
    unique: true 
}, 
type: String, 
lastvalue: { 
    type: Schema.ObjectId, 
    ref: 'event' 
}, 
owner: { 
    type: Schema.ObjectId, 
    ref: 'user', 
    require: true 
}, 
apiKey: { 
    type: String, 
    unique: true, 
    default: function() { 
     return crypto.randomBytes(64).toString('hex'); 
    } 
} 
}); 
var Device = mongoose.model('device', deviceSchema); 

我想檢索用戶的所有設備。所以: Device.find({'owner.username': req.params.username})

但它返回一個空數組! 我也試過: Device.find({'owner.username': req.params.username}, {'owner':1}) Device.find({'owner.username': req.params.username}, {'owner.$':1) 沒有任何的運氣...... 我已經搜查了整個互聯網,但我無法找到任何有用的!

回答

0

您需要首先獲取關聯用戶_id,然後使用第一個用戶查詢中的_id,在owner字段上查詢Device模型。下面顯示了這種方法:

User.findOne({ "username" : req.params.username }), 
    .exec(function(err, user) { 
     if (err) throw err; 
     Device 
     .find({"owner": user._id}) 
     .populate('owner', 'username') // only return the username 
     .exec(function(err, devices) { 
      if (err) throw err; 
      console.log(JSON.stringify(devices, undefined, 4)); 
     }); 
    } 
); 
+0

我可以在單個查詢中執行嗎? – dzervas