MongoDB访问对象属性返回undfined



我正在从我的mongoDB数据库中获取一个coach。我使用这个函数从一个对象中获取单独的属性。

exports.getCoachingTimeframes = async (id, date) => {
console.log(id, date);
const coach = await Coach.findById(id);
console.log(coach) => object
console.log(coach.name) => "name"
console.log(coach.coachingTimeframes) => undefined
return coach;
};

以下是整个coach对象:

{
_id: 'test-trainer',
name: 'Test Trainer',
status: '(Nur zum Testen...)',
image: 'https://trainingsplan-tennis.web.app/assets/trainer/test-trainer.png',
coachingTimeframes: { totalBookings: 0 },
isActive: true,
index: 100,
__v: 0
}

我真的很感谢你的帮助!

解决方案:使用JS中的ThreeDots运算符,您可以复制整个对象:

exports.getCoachingTimeframes = async (id, date) => {
console.log(id, date);
const coach = await Coach.findById(id);
const object = { ...coach };
console.log(object._doc.coachingTimeframes)
return coach;
};

如果您记录对象,您可以看到该对象的构造与控制台中显示的不同:

{
'$__': InternalCache {
activePaths: StateMachine { paths: [Object], states: [Object] },
skipId: true
},
'$isNew': false,
_doc: {
_id: 'test-trainer',
name: 'Test Trainer',
status: '(Nur zum Testen...)',
image: 'https://trainingsplan-tennis.web.app/assets/trainer/test-trainer.png',
coachingTimeframes: { totalBookings: 0 },
isActive: true,
index: 100,
__v: 0
}
}

有了这个对象的新克隆,你可以用正确的路径访问该属性,如下所示:

console.log(object._doc.coachingTimeframes)

我希望我的回答对你有帮助!

最新更新