gpt4 book ai didi

node.js - 对文档调用精益会抛出 TypeError : lean is not a function

转载 作者:行者123 更新时间:2023-12-03 08:58:36 27 4
gpt4 key购买 nike

我是 mongoose 新手,我正在尝试创建一个使用 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”已成功保存在数据库中,但是当我在填充后尝试添加 .lean() 时,出现以下错误:类型错误:savedForecast.populate(...).lean 不是函数

我在查找查询上使用过lean(),它工作得很好,但我无法让它与我的“newForecast”对象一起工作,即使“savedForecast”是一个 Mongoose 文档,正如调试器向我显示的那样。

有什么想法为什么lean() 不起作用吗?谢谢!

最佳答案

问题来自于 Document 没有 lean() 方法。

await newForecast.save(); 不会返回 Query 而是返回 Document。然后在 Document 上运行 populate 也会返回 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,因为populate必须接收回调参数,或者必须调用execPopulate(返回Promise)它。就您使用 async/await 而言,我建议使用 execPopulate 而不是回调。最后但并非最不重要的一点 - 需要了解填充的位置:

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);
}

关于node.js - 对文档调用精益会抛出 TypeError : lean is not a function,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52950167/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com