我正在嘗試按類別過濾我的寵物,我有以下寵物模型:
const Pet = mongoose.model(
'Pet',
new Schema({
name: {
type: String,
required: true,
},
age: {
type: Number,
required: true,
},
description: {
type: String,
},
weight: {
type: Number,
required: true,
},
color: {
type: String,
required: true,
},
images: {
type: Array,
required: true,
},
available: {
type: Boolean,
},
category: Object,
user: Object,
adopter: Object,
}, { timestamps: true }),
);
module.exports = Pet;
當我嘗試通過郵遞員獲取資料時,它回傳一個空陣列作為回應。
我按類別過濾的代碼:
static async getByCategory(req, res) {
const id = req.params.id;
// check if id is valid
if (!ObjectId.isValid(id)) {
res.status(422).json({ msg: 'Invalid ID' });
return;
}
const pets = await Pet.find({ 'category._id': id }).sort('-createdAt');
if (!pets) {
res.status(404).json({ msg: 'Pets not found!' });
return;
}
res.status(200).json({ pets });
}
這是我第一次使用 mongodb,所以我不確定出了什么問題。
uj5u.com熱心網友回復:
你能檢查一下你的 mongodb 確實有一個欄位“category._id”嗎?
uj5u.com熱心網友回復:
pets 檔案具有正確的資料,并通過類別檔案進行驗證

轉載請註明出處,本文鏈接:https://www.uj5u.com/net/359484.html
標籤:javascript 节点.js MongoDB 猫鼬
