node.js - Why i am not getting the data in first call to my REST API -
i making call rest api on making first call returning empty array , on second call returning desired result.here files.
mongodb.js connecting mongodb database
var mongoclient =require('mongodb').mongoclient; var dburl = 'mongodb://localhost:27017/test'; module.exports.connect = function connect(callback){ mongoclient.connect(dburl, function(err, conn){ /* exports connection */ if(err) { callback(err);console.log(err) } else { callback(undefined,conn.collection('person')); //console.log(conn) } }); };
getusers.js retrieving documents database
const mongodb = require('.././mongodb/mongodb'); var v=[]; module.exports.getuser=function(callback) { mongodb.connect(function(err,db) { if (err) { console.log(err) } else { data(db,function (docs) { //console.log(v) callback(v) }) // console.log(v) } }); } function data(db,callback) { db.find().foreach((docs)=>{ v.push(docs) }) callback(v); }
server.js starting server
const express = require('express'); const bodyparser = require('body-parser') const getusers = require('./users/getusers'); const insertusers = require('./users/insertusers'); const findusers = require('./users/findusersemail'); const delusers=require('./users/deleteusers') const moduser=require('./users/updateuser') const app = express(); app.use(bodyparser.json()) app.get('/person', (req, res) => { console.log(res.statuscode) if(res.statuscode==200) { getusers.getuser(function (userlist){ res.json(userlist); console.log(userlist); }) }}) app.listen(4569,()=>console.log('server has started on 4501'))
because data
function calls callback before data returned. correct implementation should be:
const mongodb = require('.././mongodb/mongodb'); module.exports.getuser = function(callback) { mongodb.connect(function(err, db) { if (err) { console.log(err); } else { data(db, callback); } }); } function data(db, callback) { db.find().toarray((err, docs) => callback(docs)); }
you can see global variable v
not used @ all.
by way, should follow nodejs convention implement callback function:
callback(err[, ...args])
skipping error argument give lot of pain when code base grows, when need integrate third-party libraries.
Comments
Post a Comment