访问猫鼬中的嵌套字段

时间:2020-07-03 07:02:00

标签: node.js mongodb express mongoose

我定义了两种模式,一种是用户,一种是doc。 在文档架构中,我使用createdBy字段引用用户架构

现在,当我想以文档模式显示所有记录时,我将无法访问该名称

我可以访问doc.education或doc.bio,但无法访问特定的文档名

这是我尝试过的

  doc
    .find({})
    .populate({ path: "createdBy" })
    .exec((err, docs) => {
      if (!err) {
        console.log(docs);
      }
    });

我得到这个结果

[
  {
    _id: 5efa9ab935f13d39b01f36e2,
    createdBy: {
      role: 'doctor',
      isVerified: false,
      _id: 5ef873fe544ef53874eaacfe,
      name: 'drsmira',
      email: 'drsmira@gmail.com',
      password: '$2a$10$X/52qRFCYA/DwZ6Z1ZftVu2gv.MJ4HsqXrRuB8.ZLbqj.4EVtVmBG',
      select: 'Female',
      date: 2020-12-31T00:00:00.000Z,
      phone: '342343',
      city: 'dff',
      state: 'dfss',
      specifications: [],
      __v: 0
    },
    bio: 'wweqeqwe',
    speciality: 'dentist',
    education: 'mbbs',
    treatment: 'oral care',
    location: 'ewrewre',
    hospitalList: 'sahyadri',
    awards: 'ererewrwe',
    fee: '888',
    __v: 0,
    achievements: ''
  }
]

现在我要访问名称字段。我该怎么做

我反复尝试实施

console.log(docs.createdBy.name)

但返回未定义

1 个答案:

答案 0 :(得分:0)

所以我几乎没有进行挖掘,这要感谢毗湿奴的评论

我使用forEach循环获取结果

下面是更新的代码

doc
    .find({})
    .populate({ path: "createdBy" })
    .exec((err, docs) => {
      if (!err) {
        docs.forEach((el) => {
          console.log(el.createdBy.name);
        });
        res.render("doctors", { list: docs });
      }
    });