【问题标题】:How to find an object inside an array inside a mongoose model?如何在猫鼬模型内的数组中查找对象?
【发布时间】: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


【解决方案1】:

希望你做得更好。 当我查看您的 Schema 时,我看到 item 字段是一个对象数组,其中没有 _id ,因此当您创建 catShema 的新实例时,它只会为新实例但不是items数组中的每个项目,只需输入相关项目的ID,因为根据我的理解,您的数据库中还必须有一个名为items的模型 当您将这些记录保存在数据库中时,您将生成具有此结构的元素

{
    _id: String, // auto generated
    name: String,
    items: [ {"name1", "price1", "description1", "imgUrl1", "dateAdded1", "lastUpdated1"},{"name2", "price2", "description2", "imgUrl2", "dateAdded1", "lastUpdated2"}, ...],
    dateCreated: Date,
    lastUpdate: Date
} 

注意:顶部提供的代码仅为将在数据库中注册的对象的说明,并非有效代码

这里你可以注意到在数据库内部发送的对象中没有一个名为_id的字段。 我解决这个问题的建议是

  • 要在 items 数组中创建一个名为 _id 的附加字段,例如:

    { ..., 项目: [ { _ID: { 类型:字符串, 独特的:真的, required: true // 确保在创建新实例时始终拥有它 }, ... ... // 项目的其余字段
    }, ...

现在,当您创建一个新实例时,请确保在您在数据库中输入的对象中,当您调用 catInstance.save() 时会记录 _id,因此您必须在 catInstance 对象中添加元素的当前 ID能够使用此字段进行过滤。 希望我的回答对您有所帮助,如果您还有其他问题,请告诉我 快乐编码...

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 2021-01-24
      • 1970-01-01
      • 1970-01-01
      • 2016-03-09
      • 2023-01-22
      • 2021-10-15
      • 1970-01-01
      • 1970-01-01
      • 2016-02-05
      相关资源
      最近更新 更多