目标
使用mongoose.find从mongoDB'产品'集合中按类别ID获取产品
期望的和实际的结果
所有具有匹配类别的文档应以限制数返回,但我收到一个空数组。 我尝试使用mongodb的指南针进行查询-它按预期工作。我什至尝试使用我的代码使用id(有效),title(有效)和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
}
答案 0 :(得分:0)
TL; DR:您必须将数据库中price
和category
字段中的数据转换为Number
和ObjectId
使用Mongoose查询数据时,请确保数据类型全部匹配:
通过某些操作(例如聚合,猫鼬无法轻松推断类型),猫鼬将帮助您进行转换 根据模式,但并非总是如此。最好总是 自己转换值,以避免出现类似的意外情况。
您的架构可能已更改,请确保相应地迁移和转换数据。由于猫鼬有时会为您转换值,因此,如果存储的数据与架构不匹配,它将与您尝试查询的内容不匹配。
从您的数据库输出中,我们可以推断出"price": "236.13"
和"category": "5ec120a9fc13ae248f000004"
的存储为Strings
而不是应该的Number
和ObjectId
。我们可以从"rating": 878210
和"_id": { "$oid": "5ec129e55db26438fcdb9b01" }
看到Number
和ObjectId
的表示方式。