【发布时间】:2021-04-03 05:25:28
【问题描述】:
我正在尝试查询位于猫鼬模型内的项目内的对象,当我尝试使用 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,
});
【问题讨论】:
-
items数组中的元素似乎没有_id字段。记录items给你什么? -
mongoose 自动为每个项目创建
_id字段,我可以在数据库中看到该字段,登录项目为我提供了项目数组中的所有对象(包括每个对象的_id)
标签: node.js arrays mongodb express mongoose