我刚接触到猫鼬,我正在尝试创建一个使用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);
}
}"newForecast“正在成功地保存在DB中,但是,当我尝试在填充后添加.lean()时,会得到以下错误:TypeError: savedForecast.populate(...).lean is not a function
我在查找查询上使用了lean(),它工作得很好,但是我无法让它与我的"newForecast“对象一起工作,尽管"savedForecast”是一个猫鼬文档,调试器向我展示了这一点。
你知道为什么lean()不起作用吗?谢谢!
发布于 2018-10-23 23:59:47
问题来自于Document没有lean()方法这一事实。
await newForecast.save();不返回Query,而是返回Document。然后,在populate上运行Document也会返回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);
}但是,这段代码将错误地执行--人口将不会被调用,因为populate必须接收回调参数,否则必须调用execPopulate (返回承诺)。就使用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);
}https://stackoverflow.com/questions/52950167
复制相似问题