Node.js: how to load modules without executing them? - javascript

I have a simple file model.js like follows:
var mongo = require('mongodb');
var mongoUri = process.env.MONGOLAB_URI ||
process.env.MONGOHQ_URL ||
'mongodb://localhost/mydb';
exports.connect = mongo.Db.connect(mongoUri, function(err, db) {
console.log("Connect to the database successfully")
});
and in my web.js I load the model using model = require('./model.js'). One werid thing is that although I did not call model.connect(), the message "Connect to the database successfully" still got logged to my console. Why is this happening and is there a way to avoid it?
EDIT:Never mind I have found a workaround:
exports.connect = function(){
mongo.Db.connect(mongoUri, function(err, db) {
console.log("Connect to the database successfully")
});
}

exports.connect = mongo.Db.connect(mongoUri, function(err, db) {
console.log("Connect to the database successfully")
});
You just called mongo.Db.connect() and assigned its result to exports.connect.
That code runs as soon as you require() the module.
Instead, you need to create a function:
exports.connect = function() { ... };

Related

Can Not Retrieve Nodejs MySQl Data From Database via sub function call

I have two files named login.js and dbMySql.js.
login.js is the main file that will run dbMySql.js, which is a submodule for the DB connection.
I can run getQuery() from dbMySql.js by using object.method call.
getQuery() also works fine and retrieves data from the database.
How can I get this data to my Main module from the database module? How can I return res variable to main function in login.js module
Code For login.js:
var MySqlConnect = require('./dbMySql');
var app = express();
var dbConnect = MySqlConnect("localhost", "root", "root", "mydb");
dbConnect.getQuery("select * from `test`");
console.log(dbConnect.resD);
Code For dbMySql.js:
function MySqlConnect(dbhost, dbuser, dbpassword, dbname) {
var MySqlConnect = require('mysql');
var con;
this.dbhost = dbhost;
this.dbuser = dbuser;
this.dbpassword = dbpassword;
this.dbname = dbname;
this.resultData = 'Def';
con = MySqlConnect.createConnection({
host: dbhost,
user: dbuser,
password: dbpassword,
database: dbname
})
con.connect(function (err) {
if (err) throw err;
})
function getQuery(query1) {
con.query(query1, function (err, res) {
if (err) throw err;
})
return {
resD: res
};
}
return {
getQuery: getQuery,
};
};
module.exports = MySqlConnect;
I want Retrieved Data in Main module via return method or any that will run successfully.
Vary Simple Answer I have found by run and execute after efforts.
just pass res form db to callback function parameter and run this fucntion from main module

How to use another MongoDB database using Node.js [duplicate]

How do I connect to mongodb with node.js?
I have the node-mongodb-native driver.
There's apparently 0 documentation.
Is it something like this?
var mongo = require('mongodb/lib/mongodb');
var Db= new mongo.Db( dbname, new mongo.Server( 'mongolab.com', 27017, {}), {});
Where do I put the username and the password?
Also how do I insert something?
Thanks.
Per the source:
After connecting:
Db.authenticate(user, password, function(err, res) {
// callback
});
Everyone should use this source link:
http://mongodb.github.com/node-mongodb-native/contents.html
Answer to the question:
var Db = require('mongodb').Db,
MongoClient = require('mongodb').MongoClient,
Server = require('mongodb').Server,
ReplSetServers = require('mongodb').ReplSetServers,
ObjectID = require('mongodb').ObjectID,
Binary = require('mongodb').Binary,
GridStore = require('mongodb').GridStore,
Code = require('mongodb').Code,
BSON = require('mongodb').pure().BSON,
assert = require('assert');
var db = new Db('integration_tests', new Server("127.0.0.1", 27017,
{auto_reconnect: false, poolSize: 4}), {w:0, native_parser: false});
// Establish connection to db
db.open(function(err, db) {
assert.equal(null, err);
// Add a user to the database
db.addUser('user', 'name', function(err, result) {
assert.equal(null, err);
// Authenticate
db.authenticate('user', 'name', function(err, result) {
assert.equal(true, result);
db.close();
});
});
});
var mongo = require('mongodb');
var MongoClient = mongo.MongoClient;
MongoClient.connect('mongodb://'+DATABASEUSERNAME+':'+DATABASEPASSWORD+'#'+DATABASEHOST+':'DATABASEPORT+'/'+DATABASENAME,function(err, db){
if(err)
console.log(err);
else
{
console.log('Mongo Conn....');
}
});
//for local server
//in local server DBPASSWOAD and DBusername not required
MongoClient.connect('mongodb://'+DATABASEHOST+':'+DATABASEPORT+'/'+DATABASENAME,function(err, db){
if(err)
console.log(err);
else
{
console.log('Mongo Conn....');
}
});
I find using a Mongo url handy. I store the URL in an environment variable and use that to configure servers whilst the development version uses a default url with no password.
The URL has the form:
export MONGODB_DATABASE_URL=mongodb://USERNAME:PASSWORD#DBHOST:DBPORT/DBNAME
Code to connect this way:
var DATABASE_URL = process.env.MONGODB_DATABASE_URL || mongodb.DEFAULT_URL;
mongo_connect(DATABASE_URL, mongodb_server_options,
function(err, db) {
if(db && !err) {
console.log("connected to mongodb" + " " + lobby_db);
}
else if(err) {
console.log("NOT connected to mongodb " + err + " " + lobby_db);
}
});
My version:
var MongoClient = require('mongodb').MongoClient;
MongoClient.connect('mongodb://user:pass#dhost:port/baseName', function(err, db) {
if (err) {
console.error(err);
}
var collection = db.collection('collectionName');
collection.find().toArray(function(err, docs) {
console.log(docs);
});
});
I recommend mongoskin I just created.
var mongo = require('mongoskin');
var db = mongo.db('admin:pass#localhost/mydb?auto_reconnnect');
db.collection('mycollection').find().toArray(function(err, items){
// do something with items
});
Is mongoskin sync? Nop, it is async.
Here is new may to authenticate from "admin" and then switch to your desired DB for further operations:
var MongoClient = require('mongodb').MongoClient;
var Db = require('mongodb').Db, Server = require('mongodb').Server ,
assert = require('assert');
var user = 'user';
var password = 'password';
MongoClient.connect('mongodb://'+user+':'+password+'#localhost:27017/opsdb',{native_parser:true, authSource:'admin'}, function(err,db){
if(err){
console.log("Auth Failed");
return;
}
console.log("Connected");
db.collection("cols").find({loc:{ $eq: null } }, function(err, docs) {
docs.each(function(err, doc) {
if(doc) {
console.log(doc['_id']);
}
});
});
db.close();
});
This worked for me:
Db.admin().authenticate(user, password, function() {} );
You can do it like this
var db = require('mongo-lite').connect('mongodb://localhost/test')
more details ...
if you continue to have problems with the native driver, you can also check out sleepy mongoose. It's a python REST server that you can simply access with node request to get to your Mongo instance.
http://www.snailinaturtleneck.com/blog/2010/02/22/sleepy-mongoose-a-mongodb-rest-interface/
With the link provided by #mattdlockyer as reference, this worked for me:
var mongo = require('mongodb');
var server = new mongo.Server(host, port, options);
db = new mongo.Db(mydb, server, {fsync:true});
db.open(function(err, db) {
if(!err) {
console.log("Connected to database");
db.authenticate(user, password, function(err, res) {
if(!err) {
console.log("Authenticated");
} else {
console.log("Error in authentication.");
console.log(err);
}
});
} else {
console.log("Error in open().");
console.log(err);
};
});
exports.testMongo = function(req, res){
db.collection( mycollection, function(err, collection) {
collection.find().toArray(function(err, items) {
res.send(items);
});
});
};
Slight typo with Chris' answer.
Db.authenticate(user, password, function({ // callback }));
should be
Db.authenticate(user, password, function(){ // callback } );
Also depending on your mongodb configuration, you may need to connect to admin and auth there first before going to a different database. This will be the case if you don't add a user to the database you're trying to access. Then you can auth via admin and then switch db and then read or write at will.
const { MongoClient } = require('mongodb');
// or as an es module:
// import { MongoClient } from 'mongodb'
// Connection URL
const url = 'mongodb://localhost:27017';
const client = new MongoClient(url);
// Database Name
const dbName = 'myProject';
async function main() {
// Use connect method to connect to the server
await client.connect();
console.log('Connected successfully to server');
const db = client.db(dbName);
const collection = db.collection('documents');
// the following code examples can be pasted here...
return 'done.';
}
main()
//what to do next
.then(console.log)
//if there is an error
.catch(console.error)
// what to do in the end(function result won't matter here, it will execute always).
.finally(() => client.close());
you can find more in the documentation here: https://mongodb.github.io/node-mongodb-native/4.1/
I'm using Mongoose to connect to mongodb.
Install mongoose npm using following command
npm install mongoose
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/database_name', function(err){
if(err){
console.log('database not connected');
}
});
var Schema = mongoose.Schema;
var userschema = new Schema ({});
var user = mongoose.model('collection_name', userschema);
we can use the queries like this
user.find({},function(err,data){
if(err){
console.log(err);
}
console.log(data);
});

Express js,mongodb: “ReferenceError: db is not defined” when calling a function

The code is set up this way:
var express = require('express');
var router = express.Router();
var mongo = require('mongodb').MongoClient;
function getData(){
db.collection("collection_name").find({}).toArray(function (err, docs) {
if (err) throw err;
//doing stuff here
}
var dataset = [
{//doing more stuff here
}
];
});
}
router.get("/renderChart", function(req, res) {
mongo.connect(url_monitor, function (err, db) {
assert.equal(null, err);
getData(res);
});
});
When I run the code and trying to get to /renderChart when running, I get the "ReferenceError: db is not defined". I came across a similar case, and think it may be a similar problem caused because mongodb.connect() is called asynchronously, but I couldn't get it to work:
Express js,mongodb: "ReferenceError: db is not defined" when db is mentioned outside post function
The problem here is you don't pass the db to the function, so it's undefined.
A solution:
function getData(db, res){
db.collection("collection_name").find({}).toArray(function (err, docs) {
if (err) throw err;
//doing stuff here
}
var dataset = [
{//doing more stuff here
}
];
});
}
router.get("/renderChart", function(req, res) {
mongo.connect(url_monitor, function (err, db) {
assert.equal(null, err);
getData(db, res);
});
});
You'll probably need to pass the req at some point too, or make specific db queries. And you'll probably want to use promises or async/await to better deal with all asynchronous calls.
Its Simple Javascript.
You are using a variable db in your file, which is not defined, so it will throw an error.
You need to do something like this .
var findDocuments = function(db, callback) {
// Get the documents collection
var collection = db.collection('documents');
// Find some documents
collection.find({}).toArray(function(err, docs) {
assert.equal(err, null);
assert.equal(2, docs.length);
console.log("Found the following records");
console.dir(docs);
callback(docs);
});
}
I have the same problem before, instead of passing db to routing function, My solution is to make db variable global like
var mongojs = require('mongojs')
global.db = mongojs(<mongodb url>);
then db variable can be used in any part of your code
If you're using express, put that in your app.js file and you will never have to worry about db variable anyore.
PS: some people think that using global is not a good practices, but I argue that since global is a node.js features and especially since it works, why not
node.js global variables?
You don't have tell the codes, that which database you want to use.
how to get databases list https://stackoverflow.com/a/71895254/17576982
here is the sample code to find the movie with name 'Back to the Future' in database sample_mflix > collection movies:
const { MongoClient } = require("mongodb");
// Replace the uri string with your MongoDB deployment's connection string.
const uri =
"mongodb+srv://<user>:<password>#<cluster-url>?retryWrites=true&writeConcern=majority";
const client = new MongoClient(uri);
async function run() {
try {
await client.connect();
const database = client.db('sample_mflix');
const movies = database.collection('movies');
// Query for a movie that has the title 'Back to the Future'
const query = { title: 'Back to the Future' };
const movie = await movies.findOne(query);
console.log(movie);
} finally {
// Ensures that the client will close when you finish/error
await client.close();
}
}
run().catch(console.dir);
to get list of database, put await client.db().admin().listDatabases() on fun function. e.g.
async function run() {
try {
await client.connect();
var databasesList = await client.db().admin().listDatabases();
console.log("Databases:");
databasesList.databases.forEach(db => console.log(` - ${db.name}`));
learn MongoDB more from official docs: https://www.mongodb.com/docs

trying to fetch specific data from mysql using node.js

i am new to node.js and my boss has entrusted me with a job to integrate a notification system in our attendance project..
so far i have successfully created a connection to my data base using express and mysql node modules
and the code that helped me in achieving that is given below
var express=require('express');
var mysql=require('mysql');
var app=express();
var connection=mysql.createConnection({
host:'localhost',
user:'root',
password:'',
database:'attendance'
});
connection.connect(function(error) {
if(!!error) {
console.log('Error in connection');
} else {
console.log('Connected');
}
});
app.get('/',function (req, resp) {
connection.query("Select * from employee_leaves", function (error, rows, fields) {
if (!!error) {
console.log("Error in the query");
} else {
console.log("successfully done\n");
console.log(rows);
}
});
})
app.listen(1337);
// now the issue is i want to query this statement
SELECT * from employee_leaves WHERE employee_leave_company_name ='$sup_company_name' AND leave_status='Pending'ORDER BY employee_leave_id desc"
the issue is these variable $sup_company_name is in php so
1) how should i fetch value from that variable
2)how to use where clause in node.js
Note:: $sup_company_name is declared in my require.php file
the code of require.php file is given below P.S i m accessing that variable in my other pages by include('require.php') but i dont know how to access that variable in node.js
session_start();
$sup_id = $_SESSION['employee_id'];
$sup_type=$_SESSION['employee_type'];
$sup_company_name=$_SESSION['employee_company_name'];

Express: Accessing req.session from /models/index.js

I've built a series of database queries in my express app that reside in a /models/index.js file which I can access from app.js via var express = require('express');. I am trying to populate req.session.user with a userid that is returned by a findByEmail(); function in /models/index.js.
The findByEmail(); function works fine, however I can't figure out how to store its return value in req.session. I've tried including req.session.id = result.rows[0].id; in the 'findByEmail();function, but this returns areq is not defined` error.
Am I overlooking a simple require statement in my /models/index.js file or is there another trick to accessing req.session in a module?
I've included the relevant code from /models.index.js below:
/models.index.js:
var pg = require('pg');
function findByEmail(email){
pg.connect(function(err, client, done) {
if(err) {
console.log('pg.connect error');
throw err;
}
client.query('BEGIN', function(err) {
if(err) {
console.log('client.query BEGIN error');
return rollback(client, done);
}
process.nextTick(function() {
var text = "SELECT * FROM users WHERE email = $1";
client.query(text, [email], function(err, result) {
if(err) {
console.log(err);
return rollback(client, done);
}
console.log(result);
console.log(result.rows);
console.log('id: ', result.rows[0].id);
req.session.id = result.rows[0].id;
done();
});
});
});
});
}
module.exports.pg = pg;
exports.findByEmail = findByEmail;
As far as /models/index.js knows, req is not defined, same thing with rollback. A module is a closure and you don't have access to variables defined outside of it.
If you want to do that you must pass them as parameters but it's not very good design, as #gustavohenke said: Separation of concerns.
You might want to have a callback and call it with success/error and set the session id there so you don't have to pass in into the module:
function findByEmail(email,callback){
pg.connect(function(err, client, done) {
if(err) {
console.log('pg.connect error');
throw err;
}
// Do all the async work and when you are done ...
// An error is usually passed as the first parameter of the callback
callback(err,result)
});
}
exports.findByEmail = findByEmail;
You would then call it like this:
var models = require('./models');
models.findByEmail('thedude#lebowski.com',function(err,results) {
// set session id here where you probably have access to the req object...
})

Categories

Resources