Mongoos查询未返回所需结果

时间:2020-08-27 07:35:40

标签: node.js mongodb mongoose aggregate

我必须收集用户和患者。一个用户可以有多个患者。我正在编写一个函数,该函数将发送用户详细信息以及与此相关的患者详细信息。为此,我使用猫鼬查找。我没有得到相同的结果。

const User = require('../models/User-model/user');
const Patient = require('../models/patient/patient');

患者模式

_id:ObjectID("5f469bd60ca1a76de048ef47")
patientIllness:Array
userID:"5f3ac77ae5fd03695c7f34e7"
firstName:"rahul"
lastName:"sharma"
photo:"https://picsum.photos/200/300"
age:51
gender:"male"
addressLine1:"Jamuna Paar"
adressLine2:"East Delhi"
city:"New Delhi"
pinCode:"500078"
__v:0

用户架构

_id:ObjectId("5f3ac77ae5fd03695c7f34e7")
active:"active"
email:"adishrtv10@gmail.com"
phone:"7748973500"
__v:0

功能

 patientDetails: async (req, res, next) => {
    console.log('User information will be provided');
    const {id} = req.user;

    User.aggregate(
        [
            {
                $match: {id: id},
            },
            {
                $lookup: {
                    from: 'Patient',
                    localField: '_id',
                    foreignField: 'userID',
                    as: 'patient_details',
                },
            },
            {
                $unwind: {
                    path: '$patient_details',
                    preserveNullAndEmptyArrays: true,
                },
            },
        ],
        (error, result) => {
            if (error) {
                console.log(error);
                res.send('Error');
            }
            res.send(result);
        }
    );
},

1 个答案:

答案 0 :(得分:0)

用户集合的_id类型是对象ID,患者集合的userID是字符串,您需要转换一种字段类型,并且需要使用$lookup with pipeline

  {
    $lookup: {
      from: "patient",
      as: "patient_details",
      let: { id: "$_id" },
      pipeline: [
        {
          $match: {
            $expr: {
              $eq: [
                { $toObjectId: "$userID" }, // this will convert string to object id
                "$$id"
              ]
            }
          }
        }
      ]
    }
  }

Playground

相关问题