【问题标题】:Find item in an array of Objectid references在 Objectid 引用数组中查找项目
【发布时间】:2023-03-29 23:20:01
【问题描述】:

我在 mongo 中有一个 objectIDs 引用数组。我想在填充 objectID 后获取该数组中的特定元素。问题是我得到一个空数组。 这是我的架构

// Patient Schema - start
const patientSchema = new mongoose.Schema({
    nom: {
      type: String,
      required:true
    },
    prénom: {
      type: String,
      required:true
    },
    naissance:{
      type:Date,
    },
    adresse: {
      type: String,
      required:true
    },
    téléphone: {
      type: String,
      required:true
    },
    profession: {
      type: String,
    },
    /// the field i'm trying to populate 
    consultations:[{
      type: mongoose.Schema.Types.ObjectId,
      ref:'Consultation'
    }],
    salle:{
      type: mongoose.Schema.Types.ObjectId,
      required: true,
      ref:'Salle'
    },
    date:{
      type:String,
      default: Date.now
    },
    jointes: {
      type:Array
    },
    questionnaire: {
      type:Object
    },
  }, { collection : 'patients'} );
  
  const patients = mongoose.model('Patient', patientSchema);

咨询架构

 const consultationSchema = new mongoose.Schema({
      date: {
        type: String,
        required:true
      },
      motif:{
        type: String,
      },
      observations: [{
        type: mongoose.Schema.Types.ObjectId,
        ref: "Observation"
      }],
      paiements: [{
            type: mongoose.Schema.Types.ObjectId,
            ref: "Paiement"
      }],
      ordonnances: [{
        type: mongoose.Schema.Types.ObjectId,
        ref: "Ordonnance"
      }]
    });
 const consultations = mongoose.model('Consultation', consultationSchema);

出口

  module.exports = {
    patients: patients,
    consultations: consultations,
  }

我正在尝试填充咨询字段然后获取项目的路由器

const {patients} = require('./patient.models')
const {consultations} = require('./patient.models')

// not working , getting empty array
const patient = await patients.find({"consultations.motif" : "Checking"}).populate('consultations')  
                res.send(patient)

mongo db 记录,显示该字段确实存在

这是我在不指定字段的情况下进行以下查询时得到的结果

const patient = await patients.find().populate('consultations')
        res.send(patient)

【问题讨论】:

    标签: javascript node.js mongodb mongoose


    【解决方案1】:

    这里已经回答了这个问题:Find after populate mongoose

    这是您的案例的解决方案,不涉及更改数据库结构:

    const patient = await patients.find().populate({
      path: 'consultations',
      match: {
        motif: 'Checking'
      }
    })
    res.send(patient)
    

    【讨论】:

    • 它仍然无法正常工作,我得到了所有记录。我只是在寻找带有检查主题的记录
    • 我的代码中有一个错字,也许这就是你复制它不起作用的原因。我刚刚修好了,请再试一次。
    • span class="comcopy">same.... 令人沮丧的是我 2 天以来一直在尝试解决这个问题.....
    • 我又一次拿到了所有的记录
    • 我刚刚意识到你没有错。发生的事情是 mongo 正在向我发送所有患者记录,那些没有该主题的将发送一个空数组并仍然获得患者记录,尽管如此,明白了吗?
    猜你喜欢
    • 2019-05-07
    • 2020-11-04
    • 2016-04-30
    相关资源
    最近更新 更多