Nodejs mongoose findOne 怎么合并多个结果

Nodejs mongoose findOne 怎么合并多个结果

Article.findById(aid, function (err, adoc){ adoc.user = User.findOne(adoc._id,function (err, udoc){ return udoc; }); return adoc; });

返回的是JQ对象和json的混合 怎么解决

5 回复

在使用 Mongoose 的 findOne 方法时,如果需要合并多个查询的结果,通常需要处理异步操作。上述代码中,User.findOne 是一个异步操作,而直接在回调函数中返回结果会导致逻辑上的混乱。为了解决这个问题,我们可以使用 async/await 或者 Promise 来更好地管理这些异步操作。

以下是一个改进后的示例代码,展示了如何使用 async/await 来合并多个查询的结果:

const mongoose = require('mongoose');
const Article = mongoose.model('Article', new mongoose.Schema({}));
const User = mongoose.model('User', new mongoose.Schema({}));

// 定义一个异步函数来获取文章和用户信息
async function getArticleAndUser(aid) {
    try {
        // 查找文章
        const adoc = await Article.findById(aid).exec();
        
        if (!adoc) {
            throw new Error("Article not found");
        }

        // 查找用户
        const udoc = await User.findOne({_id: adoc.userId}).exec();
        
        if (!udoc) {
            throw new Error("User not found");
        }

        // 合并结果
        adoc.user = udoc;

        return adoc;
    } catch (error) {
        console.error(error);
        return null;
    }
}

// 使用该函数
getArticleAndUser(someAid)
    .then(result => {
        if (result) {
            console.log(result);
        } else {
            console.log("Failed to fetch article or user.");
        }
    })
    .catch(err => {
        console.error("An error occurred:", err);
    });

解释

  1. 定义模型:首先确保你已经定义了 ArticleUser 模型。
  2. 异步函数:创建一个名为 getArticleAndUser 的异步函数,用于查找文章和用户信息。
  3. 查找文章:使用 await 关键字等待 Article.findById(aid) 查询完成。
  4. 查找用户:在找到文章后,使用 await 等待 User.findOne 查询完成。
  5. 合并结果:将查找到的用户信息合并到文章对象中。
  6. 错误处理:通过 try/catch 块来捕获并处理可能发生的错误。

这样,你就可以正确地合并多个查询的结果,并且避免了原始代码中的异步问题。


3级怎么办 Corpus => Article => User

Mongoose 本身可以 promise,那就可以这样写了:

var result;
Corpus.findById(corpusid)
      .populate('article')
      .exec()
      .then(function(corpus) {
         result = corpus;
         return corpus.article.populate('user').exec();       
       })
      .then(function(article) {
         result.article = article; // user已经 populate 出来了 :p           
       });

其实这个不是一个好的解决方法,你可以看 mongoose 的3.6的release notes 它已经支持 populate('parent.child')这样的写法了。

在使用 Mongoose 的 findOne 方法时,你需要理解该方法是异步的。如果你想将多个查询的结果合并在一起,你需要使用 Promise 或 async/await 来处理这些异步操作。

以下是一个示例代码,展示了如何通过 async/await 将两个查询的结果合并:

const mongoose = require('mongoose');
const Article = mongoose.model('Article', new mongoose.Schema({}));
const User = mongoose.model('User', new mongoose.Schema({}));

async function findArticleAndUser(aid) {
    try {
        // 查找文章
        const adoc = await Article.findById(aid);
        
        // 查找用户
        const udoc = await User.findOne({_id: adoc.userId});

        // 合并结果
        adoc.user = udoc;

        return adoc;
    } catch (error) {
        console.error(error);
        throw error;
    }
}

// 调用函数
findArticleAndUser('some-article-id')
    .then(result => console.log(result))
    .catch(error => console.error(error));

在这个示例中,我们使用了 async/await 来确保每个查询都完成后再进行下一步操作。最后我们将找到的用户信息添加到文章文档中。

关于返回的对象类型问题,如果你发现返回的是 JQ 对象和 JSON 的混合,那么这可能是因为你在处理过程中不小心引入了 jQuery 或其他库。建议检查你的代码以确认是否引入了不必要的库,并确保所有操作都在 Node.js 环境中正确执行。

回到顶部