【发布时间】: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