gpt4 book ai didi

node.js - 如何在 Mongoose 模型内的数组中找到对象?

转载 作者:行者123 更新时间:2023-12-03 12:17:42 25 4
gpt4 key购买 nike

当我尝试使用 find() 查找该对象时,我正在尝试查询位于 mongoose 模型内的项目内的对象。方法或 _.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”,您只能在 Mongoose 中使用该“_ID”!所以你只需要删除下划线,就是这样!这样做const item = _.find(items, { id: req.params.itemId });

关于node.js - 如何在 Mongoose 模型内的数组中找到对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65443749/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com