【发布时间】:2020-09-12 05:08:27
【问题描述】:
目标
使用 mongoose.find 从 mongoDB 'products' 集合中按类别 id 获取产品
预期和实际结果
所有具有匹配类别的文档都应该在限制数量内返回,但我收到的是一个空数组。 我尝试使用 mongodb 的指南针进行查询 - 它按预期工作。我什至尝试了我的代码来使用 id(worked)、title(worked) 和 price(没用) 来查找文档。找不到问题根的开头。
代码
产品架构和型号:
const mongoose = require('mongoose');
const productSchema = new mongoose.Schema({
title: {
type: String,
required: true,
},
thumbnail: {
type: String,
required: true,
},
price: {
type: Number,
required: true,
},
category: {
type: mongoose.Types.ObjectId,
required: true,
},
rating: {
type: Number,
default: 0,
},
voters: {
type: Number,
default: 0,
},
});
.
.
.
const Product = mongoose.model('product', productSchema);
module.exports = { Product, ... };
解析器:
products: (_, { limit, category }) => {
console.log(mongoose.Types.ObjectId('5ec120a9fc13ae248f000004')); // Works fine
Product.find({ category: mongoose.Types.ObjectId(category) }) // Tried also as a simple string, still not working
.limit(limit)
.exec((err, products) => {
if (err) console.log(err);
console.log(products);
});
if (category) return Product.find({ category }).limit(limit);
return Product.find({}).limit(limit);
},
控制台中记录的结果:
5ec120a9fc13ae248f000004
[]
收集“产品”样本:
{
"_id": {
"$oid": "5ec129e55db26438fcdb9b01"
},
"title": "Ecolab - Lime - A - Way 4/4 L",
"category": "5ec120a9fc13ae248f000004",
"thumbnail": "https://source.unsplash.com/350x390/?Automotive",
"price": "236.13",
"rating": 878210,
"voters": 2668388
},
{
"_id": {
"$oid": "5ec129e55db26438fcdb9b02"
},
"title": "Mushrooms - Black, Dried",
"category": "5ec120a9fc13ae248f000001",
"thumbnail": "https://source.unsplash.com/350x390/?Sports",
"price": "439.85",
"rating": 549879,
"voters": 2375685
},
{
"_id": {
"$oid": "5ec129e55db26438fcdb9b03"
},
"title": "Dried Figs",
"category": "5ec120a9fc13ae248f000004",
"thumbnail": "https://source.unsplash.com/350x390/?Automotive",
"price": "202.60",
"rating": 925701,
"voters": 2740499
}
【问题讨论】:
-
您的架构中定义的
price和category的类型似乎与数据库中的类型不一致。从罗盘输出中您可以看到它们存储为Strings,而它们被定义为Number和ObjectId -
@thammada 正如我所写,我还尝试将类别作为简单字符串发送到查找函数,但仍然没有获取文档
-
是的,但是由于您的架构不同,它将被转换。您需要更改架构以匹配您的数据,或更新您的数据以匹配您的架构
-
你是对的!我将集合中的所有类别字段都转换为 ObjectID 类型并且它有效。谢谢@thammada
标签: node.js mongodb express mongoose