Mongoose find()返回一个空文档
为什么这个函数返回一个空文件? 还有一个使用find({})而没有任何查询的function,它的作品。
router.get('/mesCandidatures/:id', function(req, res, next) { Models.Candidature.find({"figurant":req.params.id}, function(err,docs) { if (err){ throw err; }else{ res.send(docs); } }); });
我发送这个参数:59e5d09f853d00049fd67600
我应该收到这个:
{ "_id":"59ea0d1fea79bf099696fcab", "etat":"validé", "figurant":"59e5d09f853d00049fd67600", "offre":"59e5bc1438950e01ae45d1d2" }`
谢谢
您的问题可能是由不正确的字段typesfilter过滤造成的
你的req.params.id
是一个string,而我猜figurant
在你的模式中定义为ObjectId
types,所以你需要通过ObjectId
过滤不是一个string
改变你的代码是:
var mongoose = require('mongoose'); router.get('/mesCandidatures/:id', function(req, res, next) { Models.Candidature.find({"figurant":mongoose.Types.ObjectId(req.params.id)}, function(err,docs) { if (err){ throw err; }else{ res.send(docs); } }); });
你的代码中有一个在callback中返回的Query实例,所以在find()
情况下,你必须使用exec()
来取得mongoose来知道它何时被执行,所以你的请求应该是
router.get('/mesCandidatures/:id', function(req, res, next) { Models.Candidature.find({ figurant: req.params.id }).exec( function(err,docs) { if (err){ throw err; }else{ res.send(docs); } }); });
但是当你需要获取一个文档列表的时候,你最初使用find()
,如果你需要一个单独的文档,你可以使用findOne()
来代替查询返回一个潜在的空单个文档。 那么你可以像你那样得到你的callback:
router.get('/mesCandidatures/:id', function(req, res, next) { Models.Candidature.findOne({ figurant: req.params.id }, function(err,docs) { if (err){ throw err; }else{ res.send(docs); } }); });
此外,你不必为你的条件使用引号,除非你没有得到像"nested.field"
这样的path的嵌套字段,