在猫鼬中找到ID的所有文件?

时间:2018-12-04 05:24:24

标签: javascript mongodb mongoose

我的文件如下:

{
    "_id": {
        "$oid": "5bf662551a0ffc2f40c91945"
    },
    "categories": [
        "angular"
    ],
    "title": "1",
    "details": "1",
    "url": "undefined",
    "category": {
        "$oid": "5bf135657d6f2c69a527186d"
    },
    "created_at": {
        "$date": "2018-11-22T08:01:25.418Z"
    },
    "__v": 0
}

我想根据类别ID查找所有文档。我尝试过:

articleModel
    .find({category: req.params.id})
    .sort({ $natural: -1 })
    .exec(function(err, blogs) {
      if (err) {
        throw err;
      }
      console.log("get blogs by category ", blogs);
      res.json({
        success: true,
        message: "blogs by category",
        blogs: blogs
      });
    });

,但它返回空数组。

1 个答案:

答案 0 :(得分:1)

在使用猫鼬对象ID查找时使用new mongoose.Types.ObjectId(YOUR_ID)

articleModel
    .find({"category":  new mongoose.Types.ObjectId(req.params.id)})
    .exec(function(err, blogs) {
      if (err) {
        throw err;
      }
      console.log("get blogs by category ", blogs);
      res.json({
        success: true,
        message: "blogs by category",
        blogs: blogs
      });
    });