为何console.log输出Map类型petDetails格式异常?如何转为普通对象?
问题:如何将MongoDB返回的Map类型petDetails转为普通对象?
我在MongoDB中存储的宠物数据如下:
{ "_id" : ObjectId("0000439359317900131f111"), "name" : "Travis", "description" : "Travis is a support animal", "petId" : "225123", "petDetails" : { "color" : "brown" } }
使用以下代码尝试输出petDetails(类型为Map)时:
const pet = await context.AnimalService.findOne({where:{_id : userSubscription.planId}}) const petDetails = pet.petDetails console.log('Logging Pet Details', petDetails)
得到的输出是包含内部元数据的异常格式:
Logging Pet Details { '$__parent': '{ ' + ' _id: 0000439359317900131f111, ' + " name: 'Travis', " + " description: 'Travis is a support animal', " + " petId: '225123', " + " petDetails: Map(1) { 'color' => 'brown' }, " + ' __v: 0, ' + '}', '$__path': 'petDetails', '$__schemaType': '[object Object]' }
请问如何让petDetails以普通对象形式返回?
解决方法
1. 使用.toObject()转换整个文档(Mongoose场景)
查询返回的是Mongoose文档对象,自带内部元数据。先把整个文档转为普通JS对象,再提取petDetails:
const pet = await context.AnimalService.findOne({where:{_id : userSubscription.planId}}); const petObj = pet.toObject(); const petDetails = petObj.petDetails; console.log('Logging Pet Details', petDetails);
2. 直接将Map转为普通对象
如果petDetails确实是Map类型,用Object.fromEntries()直接转换:
const pet = await context.AnimalService.findOne({where:{_id : userSubscription.planId}}); const petDetails = Object.fromEntries(pet.petDetails); console.log('Logging Pet Details', petDetails);
3. 查询时使用.lean()(Mongoose专属)
在查询阶段直接返回普通JS对象,避免后续转换操作:
const pet = await context.AnimalService.findOne({where:{_id : userSubscription.planId}}).lean(); const petDetails = pet.petDetails; console.log('Logging Pet Details', petDetails);
内容的提问来源于stack exchange,提问作者Olympus
相关产品推荐
相关产品推荐

