【问题标题】:Return mongoose document as an object from a function [duplicate]从函数中将猫鼬文档作为对象返回[重复]
【发布时间】:2020-12-13 09:55:56
【问题描述】:

假设我有一个Post 架构,我想要一个具有这种结构的方法:

function getPostDetails(post_id)
{
    // The function searches the db for a document with that id,
    // Finds it, and returns an object containing some of its details:
    return {
        title: post.title,
        thumbnail: post.thumbnail,
        views: post.views
        // ....
    };
 }

它必须有这种形式,我有很多 async、lambda 和嵌套函数,我不想让代码变得更混乱......

我做了很多研究,但没有找到方法,可能是因为我不擅长处理承诺和异步代码?是的!

【问题讨论】:

  • 这是一个对象,没有“JSON对象”这样的东西; JSON 是一种文本格式。无论如何,您需要将函数asyncawait 里面的DB查询,然后返回对象。调用函数时,还需要await调用。 (一旦任何异步调用进入画面,您就永远无法恢复正常返回;您必须从那时起等待一切)
  • 感谢您的重播,糟糕!我的错,我刚刚编辑了!但是我认为我的确切问题是如何从查询中将数据返回到函数外部,因为从(即)mongoose.findById() 函数返回的数据仅存在于内部函数内部......
  • 返回数据正是使其可以从外部访问的原因。就做const postData = await getPostDetails(123); 还有这个参考骗子:stackoverflow.com/questions/23667086/…
  • @str 不完全是!
  • 是的,现在更清楚了。我添加了一个重复的问题,非常详细地回答了这个问题。或者,您也可以使用return Post.findById(id).exec()。详情可见documentation

标签: javascript node.js mongodb mongoose mongoose-schema


【解决方案1】:

Mongoose 调用是异步完成的。它们不能同步进行,而且使 DB 调用同步也是一个坏主意。

你有两个选择,要么让函数异步返回承诺,要么添加回调参数。

使用异步等待。

async function getPostDetails(post_id) {
  const post = await queryDb(post_id)
  const data = map(post) // convert generic post to desire schema
  return data
}

使用没有异步/等待的承诺。

function getPostDetails(post_id) {
  return queryDb(post_id).then(post => map(post))
}

使用回调。

function getPostDetails(post_id, callback) {
  queryDb(post_id).then(post => map(post)).then(post => callback(post))
}

【讨论】:

  • 非常感谢您提供的信息丰富的回答,不幸的是我无法将其应用于我的案例。我查询数据库的方式是使用Post.findById(post_id),其中 Post 是我的猫鼬模型。任何帮助将不胜感激!
猜你喜欢
  • 1970-01-01
  • 2017-10-05
  • 2021-09-26
  • 2018-01-04
  • 2011-12-19
  • 2020-12-22
  • 2016-06-20
  • 2018-03-29
  • 1970-01-01
相关资源
最近更新 更多