returning data to index.js node express - javascript

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.

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;
});
});
});

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.

Related

Node Js exiting after querying using Tedious package?

I am new to Node js and express. I trying to query my Azure database to get the list of patients(MR number). I am getting the list but I think the request.on() runs as an asynchronous function so first, it will render the HTML page without any list and after executing the function Node Js exit executing.
Code:
var express = require('express');
var router = express.Router();
//For database
var Connection = require('tedious').Connection;
var Request = require('tedious').Request;
function mrquery(connection) {
request = new Request(
"SELECT DISTINCT MRNO FROM Transaction_Record",
function(err, rowCount, rows) {
console.log(rowCount + ' row(s) returned');
process.exit();
}
);
request.on('row', function(columns) {
columns.forEach(function(column) {
console.log(column.value);
});
});
connection.execSql(request);
}
/* GET home page. */
router.get('/', async function(req, res, next) {
var connection = req.app.get('connection');
var isconnected = req.app.get('isconnected');
if (isconnected) {
mrquery(connection)
res.render('index', {
title: 'Express'
});
} else {
console.log('Not Connected');
res.render('error', {
error: 'error'
});
}
});
module.exports = router;
Thanks in advance.

"callback is not defined" in node js

This is part of my code, and it doesn't work. It says,
ReferenceError: callback is not defined
at C:\js\kweb-hw\routes\board.js:14:13
var express = require('express');
var router = express.Router();
var mysql_db = require('../db/db_con')();
var pool = mysql_db.init();
/* GET home page. */
router.get('/', function(req, res, next) {
pool.getConnection(function (err,conn) {
if(err) {
if(conn) {
conn.release();
}
callback(err,null);
return;
}
var sql = "SELECT * FROM board";
var exec = conn.query(sql,[] ,function(err, rows) {
conn.release();
if (err) throw err;
res.render('board', { rows: rows });
});
});
});
You don't need a callback in this case, because you're at the end of your route, so to speak.
So instead, you could do something like handle it with sending an error message to your rendered page.
var express = require('express');
var router = express.Router();
var mysql_db = require('../db/db_con')();
var pool = mysql_db.init();
/* GET home page. */
router.get('/', function(req, res, next) {
pool.getConnection(function (err,conn) {
if(err) {
if(conn) {
conn.release();
}
res.render('board',{rows: [],error:'Could not connect'});
}else{
var sql = "SELECT * FROM board";
var exec = conn.query(sql,[] ,function(err, rows) {
conn.release();
if (err) throw err;
res.render('board', { rows: rows });
});
}
});
});

Mongoose: .save is not a function

I'm very new and I've looked through the archives but just what's going on in this code eludes me. I used express-generator to create a calendar app and now I want to hook it up to MongoDB. The actual connection to Mongo is working, but I can't get it to save a document.
The relevant portion of my global.js (where I'm running my front-end Javascript) looks like this:
$(document).ready(function() {
var ev = new Event({ date: "a6_13_2016", time: 900, description:"Fencing"});
ev.save(function(err) {
if (err) console.log(err);
else console.log("Success!")
})
This is where I'm getting the "TypeError: ev.save is not a function" message. My models/Events.js looks like this:
var mongoose = require('mongoose');
var eventSchema = new mongoose.Schema({
date: String,
time: Number,
description: String
});
module.exports = mongoose.model('Event', eventSchema);
My routes/events.js looks like this:
var express = require('express');
var router = express.Router();
var mongoose = require('mongoose');
var Event = require('../models/Events.js');
/* GET /event listing. */
router.get('/', function(req, res, next) {
Event.find(function (err, dates) {
if (err) return next(err);
res.json(dates);
});
});
/*POST event*/
router.post('/', function(req, res, next) {
Event.create(req.body, function (err, post) {
if (err) return next(err);
res.json(post);
});
});
/* GET /event/id */
router.get('/:id', function(req, res, next) {
Event.findById(req.params.id, function (err, post) {
if (err) return next(err);
res.json(post);
});
});
module.exports = router;
I want to save something to test it, but it's giving me ".save is not a function. Other than
var events = require('./routes/events');
app.use('/events', events);
and the code establishing the Mongoose connection my app.js file is boilerplate. What do you think is the problem?
I see
$(document).ready(function() {
Are you trying to use Mongoose in browser?
It's supposed to be used on the server-side.
In browser you need to send AJAX request to the server:
$('#save').click(function() {
$.post('/event', function(response) { console.log(reposne) })
});
On the server you should add a route that will handle your AJAX request, and inside this route you can save your model:
router.post('/event', function(req, res) {
var ev = new Event({ date: "a6_13_2016", time: 900, description:"Fencing"});
ev.save(function(err) {
if (err) console.log(err);
else console.log("Success!")
})
});
Please note that you don't need the 3rd param next in your rotues. It is used only in middlewares
Are you sure that line
var Event = require('../models/Events.js');
has the correct path?
You are creating an ev object from Event function and it seems that ev is undefined, judging from the error description.
If your Event file is not properly loaded you will not have access to .save function.

MongoDB and Express: Type Error: Converting Circular structure to JSON

I am new to MEAN stack. I am trying to retreive a list of documents from MongoDB. I have used Visual Studio 2013 community edition to create a basic Nodejs Express application. Visual studio created app.js file on the root for configuration. I have put following code in app.js which is relevant to mongodb:
var mongo = require('myDB');
var db = new mongo.Db("myDB", new mongo.Server("localhost", "27017"),
{ safe: true }, { auto_reconnect: true });
// Make our db accessible to our router
app.use(function (req, res, next) {
req.db = db;
next();
});
In the routes folder that visual studio created, I have created a js file which will perform CRUD operations. I have following code in this file:
var express = require('express');
var router = express.Router();
router.get('/myRecords', function (req, res) {
var db = req.db;
db.open(function (err, db) {
if (err)
console.log(err);
else {
var collection = db.collection('myCollection');
var dataToSend = collection.find();
res.send(dataToSend);
}
})
});
module.exports = router;
I am Type Error: Converting Circular structure to JSON.
I am trying to not using any schema.
Please advice.
For those of you, who encounter the similar problem, find() doesn't return the document, we need to use toArray to retrieve documents. Following code did the trick:
router.get('/myRecords', function (req, res) {
var db = req.db;
db.open(function (err, db) { // <------everything wrapped inside this function
db.collection('myCollection', function (err, collection) {
collection.find().toArray(function (err, items) {
res.send(items);
db.close();
});
});
});
});

In a Node web app, do you open one MongoDB connection for each HTTP request?

I'm adding MongoDB to my Express.js Node web app. This is what I got so far:
// in app.js
var mongodb = require('mongodb');
var mongourl = /* … */;
// These are just examples:
app.get('/write', function (req, res) {
mongodb.connect(mongourl, function (err, db) {
db.collection('Users', function (err, coll) {
coll.insert(/* stuff */, function (err) {
res.send(200, 'Done.');
});
});
});
});
app.get('/read', function (req, res) {
mongodb.connect(mongourl, function (err, db) {
db.collection('Users', function (err, coll) {
coll.find({}, function (err, cursor) {
cursor.toArray(function (err, items) {
res.send(200, items);
});
});
});
});
});
Assuming that I want to stick with the default mongodb driver (for now):
Is this pattern right? Do I have to open a new connection to the database in each of my different routes that perform database operations?
If the pattern is right, then how do I deal with the obvious code repetition going on here? Obviously, as it stands now, the code is not acceptable.
Use the new standard, MongoClient. It manages the pool for you, defaults to 5.
//require as a module to be used anywhere.
module.exports = {}
var MongoClient = require('mongodb').MongoClient;
var mongoURI = /* … */;
MongoClient.connect(mongoURI, function(err, db) {
if(err) throw err;
module.exports.users = db.collection('users');
console.log('Connected to Mongo!')
})
then
var db = require('./db.js')
//once connected
//db.users.find()... etc
check out:
http://mongodb.github.io/node-mongodb-native/driver-articles/mongoclient.html
pooling details:
http://mongodb.github.io/node-mongodb-native/driver-articles/mongoclient.html#connection-pool-configuration
Do not close and reopen connection, you're just loosing resources :s

Categories