How to get mongodb data in koa and show it on the page

Keywords: MongoDB Database

I used koa scaffold for the project, and koa router was used for routing mongodb To connect to MongoDB

The knowledge point used here is async await. If you don't know how to use it, please read it first: Async await

Example

First, set a public method mongo.js. Here is only one query method:

var MongoClient = require('mongodb').MongoClient;
var url = 'mongodb://localhost:27017/';

module.exports = {
    /**
     * @param option
     * {
     *    tableName <String> Collection name
     *    obj <object> Query data
     * }
     */
    find:function (option={}) {
        return new Promise(function (resolve,reject) {
            MongoClient.connect(url, function(err, db) {
                if (err) throw err;
                var dbase = db.db("blog"); //Database name
                dbase.collection(option.tableName).find(option.obj).toArray(function(err, result) { // Return all data in the collection
                    if (err) throw err;
                    db.close();
                    resolve(result);
                });
            });
        })
    }
}

Then route / index.js

const router = require('koa-router')();
const mongodb = require('./common/mongo');

router.get('/list', async (ctx, next) => {
    ctx.state.appName = 'Managing blogs';
    ctx.state.data ={
        tpl:"list"
    }
    ctx.state.data.list =await mongodb.find({
        tableName:'list',
        obj:{}
    });
    await ctx.render('index/index'); //Render Page
});

Next is rendering page index.ejs. I use the EJS template engine here, as follows:

<% if(locals.data&&locals.data.list){%>
    <% for(var i = 0; i<locals.data.list.length;i++){%>
        <%= locals.data.list[i].categories%>
    <%}%>
<%}%>

The database structure is as follows:

 

Conclusion:

Let's simply say that await follows a Promise. It must be used together with async. When Promise resolve s(), the value will be assigned again. Because the read data is asynchronous, it is not only ctx.render('index/index '); it needs await,mongo.find and await

Posted by tisource on Wed, 18 Dec 2019 13:51:34 -0800