简体   繁体   中英

Find all documents by Id in mongoose?

I have the documents as follows:

{
    "_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
}

I want to find all documents based on category id. I tried this:

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

but it returns empty array.

use new mongoose.Types.ObjectId(YOUR_ID) when find using mongoose object 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
      });
    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM