node.js - 如何在猫鼬模型内的数组中查找对象?
问题描述
我正在尝试查询位于猫鼬模型内的项目内的对象,当我尝试使用find()
方法或_.find()
方法查找该对象时,由于某种原因我无法访问该对象,当我console.log()
它,它给我undefined
或者当我使用array.filter()
它时给我一个空数组,这意味着我试图访问的对象不符合我在 lodash find 方法中给它的标准,但是当我查看我的数据库时,我看到该对象确实具有满足条件的属性。所以我不知道我做错了什么,这是我的代码:如您所见,我正在尝试获取用户单击并希望查看的项目的信息:
router.get("/:category/:itemId", (req, res) => {
console.log(req.params.itemId);
//gives the item id that the user clicked on
console.log(req.params.category);
//gives the name of category so I can find items inside it
Category.findOne({ name: req.params.category }, (err, category) => {
const items = category.items; //the array of items
console.log(items); //gives an array back
const item = _.find(items, { _id: req.params.itemId });
console.log(item); //gives the value of 'undefined' for whatever reason
});
});
类别架构:
const catSchema = new mongoose.Schema({
name: {
type: String,
default: "Unlisted",
},
items: [
{
name: String,
price: Number,
description: String,
img: String,
dateAdded: Date,
lastUpdated: Date,
},
],
dateCreated: Date,
lastUpdate: Date,
});
解决方案
好吧,答案有点明显,您使用的是 MongoDB,而在 Mongo 中,您有“_ID”,您只能将“_ID”与 Mongoose 一起使用!所以你只需要删除下划线就可以了!像这样做const item = _.find(items, { id: req.params.itemId });