【问题标题】:How to navigate to nested object如何导航到嵌套对象
【发布时间】:2020-02-03 03:24:00
【问题描述】:

我在尝试使用 nodejs 和 mongodb 从嵌套对象导航到属性时遇到问题。

这是我的功能:

async function obtenerInscripciones(username) {

    const inscripcionesDB = await Inscripcion.find({ username: username._id }).populate({
        path: 'clase',
        select: '_id',
    })
    console.log(inscripcionesDB, WORKING); // **working**
    console.log(inscripcionesDB.clase._id, NOT WORKING); // **undefined**
    return inscripcionesDB;
}

我的输出是这样的

{
    estado: 'CANCELADA',
    _id: 5d959abc0d3ee404889d2b28,
    clase: { _id: 5d82e5525770f32b5024665a },
    username: 5d917b2cb531bc2a94a3d476,
  },  **WORKING**

(node:18380) UnhandledPromiseRejectionWarning: TypeError: Cannot read property '_id' of undefined, NOT **WORKING**

我做错了什么?

【问题讨论】:

    标签: node.js mongodb object nested


    【解决方案1】:

    函数前面的“异步”一词意味着一件简单的事情:函数总是返回一个承诺。

    async function obtenerInscripciones(username) {
        return await Inscripcion.find({
            username: username._id
        }).populate({
            path: 'clase',
            select: '_id',
        })
    }
    
    obtenerInscripciones(username).then((response) => {
        console.log('response', response)
    })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-13
      • 1970-01-01
      • 2019-09-17
      相关资源
      最近更新 更多