简体   繁体   中英

returning data to index.js node express

Why is users undefined?

db.js:

 var MongoClient = require('mongodb').MongoClient var users; MongoClient.connect('mongodb://127.0.0.1:27017/ExpressApp2', function(err, db) { users = db.collection('usercollection'); users.find().each(function(err, doc) { console.log(doc); }); }); 

index.js

 var express = require('express'); var router = express.Router(); /* GET Userlist page. */ router.get('/userlist', function(req, res) { var users = require('../db').getUsers(); if (users==undefined) res.send('undefined'); else res.send('found something'); }); module.exports = router; 

The collection is correctly retrieved from Mongo and logged to screen, but users in index.js gives undefined.

In db.js you are not using module.exports to export your users.

Your code in index.js suggests db.js exports an object with a getUsers function but it does not.

MongoClient.connect('mongodb://127.0.0.1:27017/ExpressApp2', function(err, db)       {
    users = db.collection('usercollection');
    users.find().each(function(err, doc) {
        console.log(doc);
    });
});

should be

module.exports.getUsers = function() {
    MongoClient.connect('mongodb://127.0.0.1:27017/ExpressApp2', function(err, db)       {
        return db.collection('usercollection');
    });
}

I'm presuming that

users.find().each(function(err, doc) {
    console.log(doc);
});

is part of your debugging and what you actually want to return is the user collection. The important bit is adding the block to module.exports as getUsers().

I got it to work with this async call in the end. index.js

router.get('/userlist', function(req, res) {
var d = require('../db');
d.getUsers('input', function(users) {
    users.each(function(err, doc) {
        res.send(doc);
        return false;
    });

});

});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM