猫鼬-FindById

时间:2020-09-18 13:38:10

标签: node.js mongodb express mongoose

我想按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);
  });
};

2 个答案:

答案 0 :(得分:1)

尝试以下操作:

console.log(req.params.id)
Location.findOne({ _id: req.params.id }).then(data => console.log(data))

OR

Location.findById(req.params.id).then(data => console.log(data))

只需检查一下,也许与布局方式有关。

我们需要确保正确获取ID,并立即使用console.log()来确保所有变量都被占用。

答案 1 :(得分:0)

我能够通过将id传递给ObjectId之前将其转换为ObjectId来解决此问题。另外,即使传递回调,也请确保您等待查询。希望这对下一个人有帮助q:

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