【发布时间】:2020-09-19 00:14:42
【问题描述】:
我想通过它的 id 从数据库中检索一个文档? findOne() 和 find() 查询按预期执行,但 findById() 没有,它返回一个空值。我究竟做错了什么???我试过硬编码一个 id,它仍然返回 null。
const getLocation = async (req, res) => {
let docById = {};
let docByField = {};
Location.findById(req.params.id, function (err, doc) {
if (err) return res.send(err);
docById = doc;
});
Location.findOne({ flag: "post" }, function (err, doc) {
console.log(doc);
if (err) return res.send(err);
docByField = doc;
});
let collection = await Location.find();
return res.json({params: req.params, docById, docByField, collection });
};
邮递员
localhost:3000/api/location/5f5fc279ff1d07315cc76a8a
{
"params": {
"id": "5f5fc279ff1d07315cc76a8a"
},
"docById": null,
"docByField": {
"coordinates": [
12.2384,
47.4309843
],
"_id": "5f641abaa8ac9049a0e40c18",
"__v": 0,
"flag": "post",
"type": "Point"
},
"collection": [
{
"coordinates": [
-73.856077,
40.848447
],
"_id": "5f5fc279ff1d07315cc76a8a",
"type": "Point",
"flag": "profile"
},
{
"coordinates": [
12.2384,
47.4309843
],
"_id": "5f641abaa8ac9049a0e40c18",
"__v": 0,
"flag": "post",
"type": "Point"
}
]
}
已解决
//transform string into id object
const { Types } = require("mongoose");
const toObjId = (id) => {
return Types.ObjectId(id);
};
const getLocation = async (req, res) => {
await Location.findById(toObjId(req.params.id), function (err, doc) {
if (err) return res.send(err);
return res.send(doc);
});
};
【问题讨论】:
-
尝试在
findById的回调函数中添加console.log(doc)。getLocation函数有可能在调用findById方法的回调之前返回响应。 -
控制台日志也显示为空。
标签: node.js mongodb express mongoose