找不到_id在mongodb中工作 [英] Find with _id not working in mongodb
问题描述
我有一个名为Releases的集合,它包含一个名为product的子文档。
我的收藏如下:
I have a collection named Releases that holds a subdocument named product. My collection looks like this:
{
"_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
}
我试图找到所有与特定产品相关的版本。
I am trying to find all releases associated to a specific product.
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 / 并尝试将其应用于我的代码,但我无法使其工作。
But it gives me an empty array if i console.log(releases) I've been stuck with this for a while and asking u guys for help. What am i doing wrong. I read the documentation on https://docs.mongodb.com/manual/tutorial/query-embedded-documents/ and tried to apply that to my code but i cant get it to work.
我的架构如下所示:
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);
推荐答案
您需要更改 id
从字符串到mongoose objectId
You need to change your id
from string to 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);
})
这篇关于找不到_id在mongodb中工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!