#Nodejs mongoose 使用mongoose 多个条件查询如何设计

#Nodejs mongoose 使用mongoose 多个条件查询如何设计

** 需要实现的功能 ** 我想使用mongoose分别查询出条件= type:0 type:1 type:2 type:3 这里是四组数据 通过调用方法 db.prototype.findByType=function(query,callback){ db.find(type:query,callback); }; 然后将这些数据分别吐到前端 ejs遍历显示 如果调用四次数据根本拿不到就已经跳到前端了 因为是异步的除非一次次的嵌套 我感觉那样写太乱了 请问大家有什么好办么?

在调用的时候我想是这样 var a,b,c,d; db.findByType(0,function(doc,err){a=doc;}); //然后通过 render(‘index’,a:a,b:b…


4 回复

当然可以!你提到的需求是使用 Mongoose 进行多个条件查询,并且希望以非嵌套的方式处理这些异步操作。这里我们可以使用 Promise 或者 async/await 来简化异步代码。

示例代码

首先,我们定义一个方法来处理多个条件查询,并返回一个 Promise:

const mongoose = require('mongoose');
const db = require('./models'); // 假设你已经有一个 Mongoose 模型实例

// 定义一个方法来根据类型查询数据
db.prototype.findByType = async function (type) {
    try {
        const docs = await db.find({ type }).exec();
        return docs;
    } catch (err) {
        throw new Error(`Failed to find documents by type ${type}: ${err.message}`);
    }
};

// 主函数来同时获取所有类型的文档
async function fetchAllTypes() {
    try {
        const [docs0, docs1, docs2, docs3] = await Promise.all([
            this.findByType(0),
            this.findByType(1),
            this.findByType(2),
            this.findByType(3)
        ]);

        // 将结果传递给前端
        res.render('index', { a: docs0, b: docs1, c: docs2, d: docs3 });
    } catch (err) {
        console.error(err);
        res.status(500).send('Internal Server Error');
    }
}

解释

  1. 定义 findByType 方法

    • findByType 方法接收一个类型参数 type
    • 使用 await 关键字等待 Mongoose 查询的结果。
    • 如果查询成功,则返回结果;如果失败,则抛出错误。
  2. 使用 Promise.all

    • fetchAllTypes 函数中,我们使用 Promise.all 同时执行四个查询。
    • Promise.all 会等待所有 Promise 都完成,并返回一个包含每个 Promise 结果的数组。
  3. 处理结果并渲染视图

    • fetchAllTypes 函数中,我们将四个查询的结果分别赋值给 docs0, docs1, docs2, docs3
    • 最后,将这些结果传递给 EJS 模板进行渲染。

总结

这种方法利用了 Promiseasync/await 的强大功能,使得异步代码更加简洁易读。通过这种方式,你可以避免回调地狱(callback hell),并且可以轻松地管理多个异步操作。


解决了 自定义了个递归方法 来 递归func 到最后一个func结束递归并render

你递归那不是变成串行 应该 声明个代理 例如 proxy = new proxy(‘a’,‘b’,‘c’,function(a,b,c){ render(‘index’,…)}) db.findByType(0,function(doc,err){emit(‘a’,doc)}); db.findByType(1,function(doc,err){…); db.findByType(2,function(doc,err){…); 然后ba la ba la…

在使用 Mongoose 进行多个条件查询时,可以利用 Promiseasync/await 来处理异步操作,避免回调地狱(callback hell)。以下是一个示例,展示了如何实现并发查询,并在所有查询完成后渲染前端页面。

示例代码

首先,确保你的 Mongoose 模型定义正确:

const mongoose = require('mongoose');

const YourModelSchema = new mongoose.Schema({
    type: Number,
    // 其他字段...
});

const YourModel = mongoose.model('YourModel', YourModelSchema);

然后,你可以使用 Promise.all 来并行执行多个查询:

const db = require('./your-db-connection'); // 假设这是你的数据库连接文件

db.prototype.findByType = async function(query) {
    try {
        const docs = await YourModel.find({ type: query }).exec();
        return docs;
    } catch (err) {
        console.error(err);
        throw err;
    }
};

module.exports = db;

// 在你的路由处理函数中:
const db = require('./your-db-connection');
const express = require('express');
const app = express();

app.get('/data', async (req, res) => {
    try {
        const [type0, type1, type2, type3] = await Promise.all([
            db.findByType(0),
            db.findByType(1),
            db.findByType(2),
            db.findByType(3)
        ]);

        res.render('index', { a: type0, b: type1, c: type2, d: type3 });
    } catch (err) {
        console.error(err);
        res.status(500).send('Internal Server Error');
    }
});

解释

  1. 模型定义:定义了一个 Mongoose 模型 YourModel
  2. findByType 方法:使用 async/await 来简化异步操作。
  3. Promise.all:用于并行执行多个查询。当所有查询完成时,结果会按顺序返回。
  4. 路由处理:在一个路由处理函数中,同时获取四个类型的数据,并在所有数据准备好后渲染前端页面。

这种方式避免了回调嵌套的问题,并且代码更易读、维护。

回到顶部