【问题标题】:How to cast a mongoose aggregate result to a specific document schema type?如何将猫鼬聚合结果转换为特定的文档模式类型?
【发布时间】:2018-06-21 04:06:48
【问题描述】:

考虑以下聚合:

let getUsersWithNoPersonsPromise = () => {

        let pipeline = [
            {
                $lookup: {
                    from: "persons",
                    localField: "id",
                    foreignField: "person_id",
                    as: "persons_users"
                }
            },
            {
                $match: {
                    "persons_users:0": {
                        $exists: false
                    }
                }
            }
        ];


        return User.aggregate(pipeline).exec();
}

如何将 $match 结果转换为 UserModel 类型?我得到了普通的 javascript 对象,我希望收到猫鼬用户类型的对象。

【问题讨论】:

    标签: mongodb mongoose casting aggregation-framework aggregate


    【解决方案1】:

    您可以使用聚合查询的结果并简单地通过遍历结果数组来实例化新对象,就像这样(假设您使用的是异步等待);

    let people = await getUsersWithNoPersonsPromise()
    people = people.map(p => new Person(p))
    

    【讨论】:

      【解决方案2】:

      你可以用这个:

      const { Query } = require('mongoose');
      const mongooseQuery = new Query();
      
      // pass the model and filter to mongoose to cast
      // you can add this to pre aggregation middleware
      mongooseQuery.cast(Model, filter);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-08-22
        • 2017-07-08
        • 1970-01-01
        • 1970-01-01
        • 2021-07-22
        • 2014-12-21
        • 2017-06-06
        • 2019-12-10
        相关资源
        最近更新 更多