【问题标题】:Iterating through a MongoDB Object Attribute遍历 MongoDB 对象属性
【发布时间】:2021-08-28 03:00:02
【问题描述】:

我有一个 Nestjs Rest API,我正在尝试从 MongoDB 查询一个对象。这是我在services.ts 文件中使用的代码。

    async findScore(id: string) {
    // Error Handling - Irrelevant to question
    if (!isValidObjectId(id)) return errorRes(HttpStatus.BAD_REQUEST, Messages.NOT_AN_ID)
    
    // Mongoose query to fetch object
    const existingAssessments = await this.assessmentModel.findById(id).lean()

    // Error Handling - Irrelevant to question
    if (!existingAssessments) return errorRes(HttpStatus.BAD_REQUEST, Messages.notFound("ASSESSMENT"))

    // Printing the queried object - THIS WORKS FINE - Prints the entire object
    console.log(existingAssessments)

    // Printing the answers array (array of array of booleans) of the queried object - THIS WORKS FINE - Prints [[true, false]]
    console.log(existingAssessments.answers)


    for (let answerArr in existingAssessments.answers) {
        // Printing the answers in each array of the queried object - THIS PRINTS OUT 0
        console.log(answerArr)
    }
}

控制台日志语句的输出如下所示。

我刚刚查询的对象有一个名为answers 的属性,它是一个包含布尔值的数组。

在第一个 console.log 语句中,我打印了整个对象。 - 工作正常

在第二个 console.log 中,我单独打印 answers 属性。 - 工作正常

当我遍历 answers 数组以打印它们的值时,它总是打印 0。这实际上应该打印包含布尔值的子数组。

这就是我的 Mongo Schema 是如何为此属性定义的

answers: {
    type: [
        [{
            type: Boolean
        }]
    ],
    required: false
}

这就是我的 DTO 查找此属性的方式。

@IsNotEmpty()
@IsArray()
answers: Boolean[][]  

请帮我打印 MongoDB 中查询对象的布尔数组数组中的值。

【问题讨论】:

    标签: typescript mongodb mongoose nestjs mongoose-schema


    【解决方案1】:

    您需要使用for ... of 而不是for ... in

     // Printing the answers array (array of array of booleans) of the queried object - THIS 
     
    existingAssessments = { answers: [[true, false]] }
    console.log(existingAssessments.answers)
    
    
    for (let answerArr of existingAssessments.answers) {
        console.log(answerArr)
    }

    for in 循环遍历对象的可枚举属性名称。

    for of(ES6 中的新功能)确实使用 object-specific iterator 并循环由它生成的值。

    【讨论】:

    • 不敢相信我错过了。非常感谢!
    【解决方案2】:
    let arr = ['el1', 'el2', 'el3'];
    
    arr.addedProp = 'arrProp';
    
    // elKey are the property keys which in your case is "0"
    for (let elKey in arr) {
      console.log(elKey);
    }
    
    // elValue are the property values which in your case is array of 
    for (let elValue of arr) {
      console.log(elValue)
    }
    

    【讨论】:

      猜你喜欢
      • 2012-01-08
      • 2016-05-12
      • 1970-01-01
      • 1970-01-01
      • 2014-08-09
      • 1970-01-01
      • 2021-02-15
      相关资源
      最近更新 更多