【问题标题】:how to find in an Array of Objects by id?如何通过 id 在对象数组中查找?
【发布时间】:2021-09-04 01:20:59
【问题描述】:

我想使用 mongoose 通过 id 在对象数组中查找。

我有这个清单:

 {
   "data":[
      {
         "_id":"60ce0ea7eb945a22288fd0ba",
         "parent":"50ce0e44eb945a22288fd0b1",
         "label":"label 1-2",
         "ancestors":[
            {
               "_id":"50ce0e44eb945a22288fd0b1",
               "label":"label 1-1"
            },
            {
               "_id":"40ce077e90c6262bdc21aa44",
               "label":"label 1"
            }
         ]
      },
      {
         "_id":"50ce0e44eb945a22288fd0b1",
         "parent":"60ce077e90c6262bdc21aa55",
         "label":"label 1-1",
         "ancestors":[
            {
               "_id":"40ce077e90c6262bdc21aa44",
               "label":"label 1"
            }
         ]
      },
      {
         "_id":"40ce077e90c6262bdc21aa44",
         "parent":null,
         "label":"label 1",
         "ancestors":[]
      }
   ]
}

这是架构:

const categorySchema = new mongoose.Schema(
  {
    label: {
      type: String,
      required: true
    },
    parent: {
      type: ObjectId,
      default: null,
      ref: 'category'
    },
    ancestors: [
      {
        _id: {
          type: ObjectId,
          ref: 'category'
        },
        label: String
      }
    ]
  },
  { timestamps: true }
);

我尝试过这样做:

  async getDescendants(req, res) {
    let { pId } = req.body;
    if (!pId) {
      return res.json({ error: 'All filled must be required' });
    } else {
      try {
        const data = await patternModel
          .find({ 'ancestors._id': pId })
          .select({
            _id: false,
            label: true
          })
          .exec();
   
        if (data) {
          return res.json({ data });
        }
      } catch (err) {
        return res.json({ err: err });
      }
    }
  }

这是我的实际结果:

{
  "data": []
}

当我将 .find({ 'ancestors._id': pId }) 更改为 .find({ 'ancestors.label': label }) 时,它可以工作,但不适用于 id。

【问题讨论】:

  • 你试过祖先[_id] 或祖先[pId] 吗?!
  • @Program_Lover 我试过.find({ 'ancestors[_id]': pId }),但没用。
  • @Program_Lover 我添加了猫鼬模式也许会有所帮助。

标签: node.js mongoose mongoose-schema


【解决方案1】:

这不是一个简单的领域。它是一个子文档数组。使用elemMatch

编辑:查询 _id 字段时,您必须将它们转换为 ObjectIds(特定于 Mongo)。

let newPid = mongoose.Types.ObjectId(pId);

 const data = await patternModel.find({ ancestors: { $elemMatch : { _id: newPid} }  })
.select({ _id: false,label: true })
.exec();

【讨论】:

  • 我试过这个.find({ ancestors: { $elemMatch: { _id: pId } } }),但没用。
  • let newPid = mongoose.Types.ObjectId(pId);。添加这个并在查询中将 pId 替换为 newPid。
  • ty,我在顶层导入了const mongoose = require('mongoose');,它可以工作。
  • 没有 mongoose.Types.ObjectId(pId); 是否可以工作?
  • find() 中缺少一个右大括号。你可以编辑它吗?
猜你喜欢
  • 2022-11-10
  • 2020-02-29
  • 2014-03-10
相关资源
最近更新 更多