如何在猫鼬模型内的数组内查找对象?

Pen*_*gin 5 arrays mongoose mongodb node.js express

我正在尝试查询猫鼬模型内的项目内的对象,当我尝试使用方法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
    });
  });
Run Code Online (Sandbox Code Playgroud)

类别架构:

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,
});
Run Code Online (Sandbox Code Playgroud)

小智 1

答案有点明显,您正在使用 MongoDB,并且在 Mongo 中您有“_ID”,您只能在 Mongoose 中使用该“_ID”!所以你只需删除下划线即可!像这样做const item = _.find(items, { id: req.params.itemId });