[英]mongoose find doesn't return any doc, while compass does
目標
使用 mongoose.find 從 mongoDB 'products' 集合中按類別 id 獲取產品
預期結果和實際結果
具有匹配類別的所有文檔都應返回限制數,但我收到的是一個空數組。 我嘗試使用 mongodb 的指南針進行查詢 - 它按預期工作。 我什至嘗試了我的代碼來使用 id(worked)、title(worked) 和 price(沒用) 來查找文檔。 找不到問題根源的開頭。
代碼
產品架構和 model:
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
}
TL;DR:您必須將數據庫中price
和category
字段的數據轉換為Number
和ObjectId
當您使用 ZCCADDEDB567ABAE643E15DCF0974E503Z 查詢數據時,請確保數據類型全部匹配:
通過一些操作(如聚合,其中 mongoose 將幫助您根據架構進行轉換,但並非總是如此。 最好總是自己轉換值以避免這樣的意外。
您的架構可能已更改,請確保相應地遷移和轉換數據。 由於 mongoose 有時會為您轉換值,如果存儲的數據與架構不匹配,它將與您嘗試查詢的內容不匹配。
從您的數據庫 output 中,我們可以推斷出"price": "236.13"
和"category": "5ec120a9fc13ae248f000004"
ObjectId
為Strings
而不是Number
和對象 ID。 我們可以從"rating": 878210
和"_id": { "$oid": "5ec129e55db26438fcdb9b01" }
中看到Number
和ObjectId
是如何表示的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.