【问题标题】:Mongoos lookup not return the desired results猫鼬查找不返回所需的结果
【发布时间】:2020-12-16 01:24:09
【问题描述】:

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

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);
        }
    );
},

【问题讨论】:

    标签: node.js mongodb mongoose aggregate


    【解决方案1】:

    用户集合的_id类型是Object 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

    【讨论】:

    • 我从前端获取输入 id 作为字符串。我正在使用它来查找用户,然后查找与之相关的患者。我认为,使用 isMatch 时存在问题,因为我们仍在将对象 ID 与字符串进行比较。我该如何解决这个问题?
    • 使用_id: mongoose.Types.ObjectId(id)将字符串转换为对象id再试试。
    • 这是有效的,但我无法查看患者详细信息以及用户详细信息。我只看到用户详细信息。我正在这样做。 const result = await User.aggregate([ { 代码 ]); res.send(结果);
    • 检查patient 集合中userID 字段的类型是它的对象还是字符串?并检查我在回答中预测的集合名称patient,但您可以根据您的数据库进行更正。可能是您的查询中的大写,我在小范围内使用过
    • 实际上,我将 userID 更改为 ObjectId 类型并通过以下方式更改了您的代码管道: [ { $match: { $expr: { $eq: ['$userID', '$$id '], }, }, }, ],集合名称已更正
    猜你喜欢
    • 1970-01-01
    • 2014-05-30
    • 2017-12-03
    • 2015-08-26
    • 2014-07-25
    • 2018-08-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多