Luc*_* P. 2 mongoose mongodb node.js
我是猫鼬新手,我正在尝试创建一个使用 OpenWeatherMap API 的应用程序。从 API 请求数据后,我将它们保存到我的 MongoDB 中,然后我想以 json 形式返回结果,因此我调用以下函数:
async function saveForecast(data) {
// Code here for creating the "forecastList" from the data and fetching the "savedLocation" from the DB
const newForecast = new Forecast({
_id: new mongoose.Types.ObjectId(),
location: savedLocation,
city: {
id: data.city.id,
name: data.city.name,
coordinates: data.city.coord,
country: data.city.country
},
forecasts: forecastList
});
try {
const savedForecast = await newForecast.save();
return savedForecast.populate('location').lean().exec(); //FIXME: The lean() here throws TypeError: savedForecast.populate(...).lean is not a function
} catch (err) {
console.log('Error while saving forecast. ' + err);
}
}
Run Code Online (Sandbox Code Playgroud)
“newForecast”已成功保存在数据库中,但是当我在填充后尝试添加 .lean() 时,出现以下错误:
TypeError: savedForecast.populate(...).lean is not a function
我在查找查询上使用了lean(),它工作得很好,但我无法让它与我的“newForecast”对象一起工作,即使“savedForecast”是一个猫鼬文档,正如调试器向我显示的那样。
有什么想法为什么lean() 不起作用吗?谢谢你!
小智 5
问题出在Document
没有lean()
方法。
await newForecast.save();
不返回 aQuery
而是返回 a Document
。然后运行populate
aDocument
也会返回Document
。要转换Document
为普通 JS 对象,您必须使用Document.prototype.toObject()方法:
try {
const savedForecast = await newForecast.save();
return savedForecast.populate('location').toObject(); // Wrong! `location` is not populated!
} catch (err) {
console.log('Error while saving forecast. ' + err);
}
Run Code Online (Sandbox Code Playgroud)
然而,这段代码将错误地执行 - 人口将不会被调用,因为populate
必须接收回调参数或execPopulate
(返回一个 Promise)必须对其进行调用。就您使用的情况而言,async/await
我建议您使用execPopulate
回调而不是回调。最后但并非最不重要的一点是——人口location
需要倾斜:
try {
const savedForecast = await newForecast.save();
return await savedForecast
.populate({ path: 'location', options: { lean: true }})
.execPopulate()
.then(populatedForecast => populatedForecast.toObject());
} catch (err) {
console.log('Error while saving forecast. ' + err);
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
4222 次 |
最近记录: |