找不到_id在mongodb中工作

时间:2018-05-31 15:37:26

标签: javascript mongoose

我有一个名为Releases的集合,它包含一个名为product的子文档。 我的收藏如下:

{
 "_id": ObjectId("5b1010e4ef2afa6e5edea0c2"),
  "version": "abc",
  "description": "<p>abc</p>\n",
  "product": {
    "_id": ObjectId("5b100c9949f43c6b6f10a93f"),
    "name": "Product 1",
    "description": "<p>abc</p>\r\n",
    "image": "Product 1.png",
    "__v": 0
  },
  "releasedate": ISODate("2018-05-30T00:00:00Z"),
  "__v": 0
}

我正在尝试查找与特定产品相关的所有版本。

   var id = req.body.productId
   var query = {'product._id' : id};
   Release.find(query)
   .select('_id version description product releasedate')
   .sort({releasedate: 1 })
   .exec()
   .then(releases => {
     console.log(releases);
     res.status(200).json(releases);
   })

但如果我在console.log(发布),它会给我一个空数组 我已经坚持了一段时间,并请求你们帮忙。我究竟做错了什么。我阅读了https://docs.mongodb.com/manual/tutorial/query-embedded-documents/上的文档并试图将其应用到我的代码中,但我无法使其工作。

我的架构如下所示:

   var mongoose = require('mongoose');
   var Schema = mongoose.Schema;

   var Product = new Schema({
   _id: Schema.Types.ObjectId,
   name: String,
   description: String,
   image: String,
   });
   module.exports = mongoose.model('Product', Product);

1 个答案:

答案 0 :(得分:1)

您需要将id从字符串更改为mongoose objectId

var id = req.body.productId
   var query = {'product._id' : mongoose.Types.ObjectId(req.body.productId)};
   Release.find(query)
   .select('_id version description product releasedate')
   .sort({releasedate: 1 })
   .exec()
   .then(releases => {
     console.log(releases);
     res.status(200).json(releases);
   })