在Mongoose中使用ObjectID的数据模型参考

我有两个mongoose模型的用户和请求。 一个用户可以有多个请求。 为了链接这两个数据模型,我在Request模型中引用用户的objectID。 但是,当我试图获取一个特定的用户ID的所有请求,我没有得到任何结果。

用户

var UserSchema = new Schema({ name: String, username: String }); module.exports = mongoose.model('User', UserSchema); 

要求

 var RequestSchema = new Schema({ type: String, user_id: { type : mongoose.Schema.Types.ObjectId, ref: 'User'} }); module.exports = mongoose.model('Request', RequestSchema); 

以下是根据URL中传递的用户标识提取请求的示例代码

 exports.getRequests = function (req, res, next) { var userId = req.params.id; console.log('USER ID'+userId); Request.findOne({'user_id': 'kenan'}, function (err, request) { if (err) return next(err); if (!requests){ console.log('NO REQUEST FOUND'); return res.send(401); } res.json(request); }); }; 

我知道我正在使用findOne,这将返回给我一个单一的资源。 然而,这是失败的,我没有得到任何结果。 我在我的数据库中填充了数据。 以下是获取请求的URL。

 http://localhost:9000/api/V1/users/547ee1e82e47bb982e36e433/requests 

请帮助build议我在这里做错了什么。

谢谢

一旦你做了find()你需要填充对用户的引用。

  • 一旦find所有请求,就需要parsing对用户的引用。 使用填充来parsing引用。
  • parsing后,根据您正在search的name筛选请求。

更新的代码:

 Request .find().populate({'path':'user_id',match:{'name':'kenan'}}) .exec(function (err, resp) { var result = resp.filter(function(i){ return i.user_id != null; }); console.log(result); }) 

好的,上面的回答是正确的,谢谢你的回应。 我错误地填充了我的请求集合。 这是每个人的知识。 如果将对象ID引用作为集合中的一个字段,请确保您插入的是ObjectID对象而不是数值。

错误

 { "_id" : ObjectId("54803ae43b73bd8428269da3"), "user_id" : "547ee1e82e 47bb982e36e433", "name" : "Test", "service_type" : "test", "version" : "10" , "environment" : "test", "status" : "OK", "__v" : 0 } 

正确

 { "_id" : ObjectId("54803ae43b73bd8428269da3"), "user_id" : ObjectId("547ee1e82e 47bb982e36e433"), "name" : "test", "service_type" : "test", "version" : "10" , "environment" : "test", "status" : "OK", "__v" : 0 }