【问题标题】:How to get the first item of an array field I get with populate in mongoose?如何获取我在猫鼬中填充的数组字段的第一项?
【发布时间】:2022-10-01 19:20:58
【问题描述】:

我有一个 mongodb 集合,当我从数据库返回数据时,我想填充一个嵌套字段。我只想返回特定字段,下面的代码解释更多。

this is my schema

const hallSchema = new Schema({
  hallName: { type: String, required: true },
  email: { type: String, required: true },
  images: [{ type: String, required: true }],
});

这是我正在编写的用于获取图像数组的第一张图像的代码

chatRooms = await ChatRoom.find({ _id: convertedIds })
      .populate(\"hallId\", `hallName ${images[0]}`);

上面的查询失败,因为它无效, 如何获得图像数组的第一项? 谢谢你的帮助

    标签: javascript node.js mongodb find populate


    【解决方案1】:

    我的理解是,您想在hallId 中填充数据,并从填充的hallId 数据中选择图像数组中的第一张图像。因此,要从填充数据中投影字段,您可以这样做, 这个对我有用,

    const chatRooms = await ChatRoom.find({ _id: convertedIds })
        .populate({ path: 'hallId', select: {
            hallName: 1,
            images: { $slice: ['$images', 1] },
        }
    });
    

    【讨论】:

    • 太好了,很高兴听到。
    猜你喜欢
    • 1970-01-01
    • 2021-06-15
    • 2020-09-13
    • 2021-01-25
    • 1970-01-01
    • 2016-04-25
    • 2021-05-06
    • 2016-06-11
    • 2020-01-30
    相关资源
    最近更新 更多