在mongodb中获取数据时出现问题,请按类别id获取



我正在尝试按类别筛选我的宠物,我有以下宠物模型:

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;

当我试图通过poster获取数据时,它会返回一个空数组作为响应。

我要按类别筛选的代码:

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,所以我不确定出了什么问题。

客户端传递的id是字符串,保存在数据库中的是ObjectId。将字符串转换为Pet.find()之前的Mongoose ObjectId。

const id = mongoose.Types.ObjectId(req.params.id);
const pets = await Pet.find({ 'category._id': id }).sort('-createdAt');

别忘了导入"猫鼬"。

您能检查一下您的MongoDB是否确实有一个字段category._id吗?

最新更新