首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >调用精益文档引发TypeError:精益不是一个函数

调用精益文档引发TypeError:精益不是一个函数
EN

Stack Overflow用户
提问于 2018-10-23 13:19:38
回答 1查看 3.1K关注 0票数 1

我刚接触到猫鼬,我正在尝试创建一个使用OpenWeatherMap API的应用程序。在从API中请求数据后,我将它们保存到我的MongoDB中,然后以json的形式返回结果,因此调用以下函数:

代码语言:javascript
复制
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()不起作用吗?谢谢!

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-10-23 23:59:47

问题来自于Document没有lean()方法这一事实。

await newForecast.save();不返回Query,而是返回Document。然后,在populate上运行Document也会返回Document。要将Document转换为普通的JS对象,必须使用Document.prototype.toObject()方法:

代码语言:javascript
复制
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需要倾斜:

代码语言:javascript
复制
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);
}
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52950167

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档