i have been trying to connect to my local mongodb using mongojs package but its not connecting at all. i have my mongo service running on http://127.0.0.1:27017/ and below is my code :
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var mongo= require('mongojs');
var db=mongo('catalog',['products']);
app.use(bodyParser.json);
//adding our first route name
db.on('connect', function () {
console.log('database connected')
})
app.get('/',function(req,res){
res.send('It Worked');
});
app.get('/products',(req,res)=>{
db.products.find(function (err,docs) {
if (err) {
res.json(err)
}else{
res.json(docs)
}
})
});
i have set event on connect to log if the connection is established but nothing is showing up.do you i could use mongoose or some other packages if it doesnt work at all?
mongojs doesn't fire the connect function until you make the first request to a collection. Make a request to your collection and the on('connect') function will fire.
Or in your case go to /products in your browser and you can see the database connected log in your terminal.
If you want to request records from your collection without going to /products in your browser then just write your query outside of your app.get('/products').
Make sure you add
app.listen(3000, function() {
console.log('server is running');
});
at the the end and go to localhost:3000/products in your browser.
Related
I am using node-run-cmd package to start the mongodb server in my app.js file. I know this works because I can see the collections on Robomongo when my script is running as well as the mongod.exe in my list of running processes. The problem is trying to connect to the db called testDB. Below is the commented code.
//start mongodb server
//this works
var nrc = require('node-run-cmd');
var cmd = '..\\mongodb\\mongod --dbpath '+__dirname+'\\db';
nrc.run(cmd);
//setup
var express = require('express');
var MongoClient = require('mongodb').MongoClient;
var app = express();
app.use(express.static('public'));
app.set('view engine', 'ejs');
//connect to mongo
//this fails to connect to db testDB
var url = 'mongodb://localhost:27017/testDB';
MongoClient.connect(url, function(err, db) {
if(!err) {
console.log("connection successful");
}
else{
console.log(err.message)
}
});
Here is the err.message
failed to connect to server [localhost:27017] on first connect
Any idea what I am doing wrong here. My assumption is that the db connection is trying before the server has fully started but I am not completely sure.
EDIT:
so that's what it was, timing issue. I tried the following and it connected to the DB. Is there a graceful way of doing this other than what I have here?
function connect(){
var url = 'mongodb://localhost:27017/testDB';
MongoClient.connect(url, function(err, db) {
if (!err) {
console.log("connection successful");
}
else {
console.log(err.message)
}
});
}
setTimeout(connect, 10000);
You should use the callback in the node_run_cmd package (https://www.npmjs.com/package/node-run-cmd#callback-style).
Place your connect function inside the callback.
You will probably also want to only start express here as well.
I have a locally hosted mongodb that I can connect to using mongodb.MongoClient.
Working code:
var mongoClient = require("mongodb").MongoClient;
...
var startApp = function(db) {
// Get our collections in an easy to use format
var database = {
chats: db.collection('chats'),
messages: db.collection('messages')
};
// Configure our routes
require('./app/routes')(app, database);
// START APP
// Start app on port
app.listen(port);
// Tell user the app is running
console.log("App running on port " + port);
// Expose app
exports = module.exports = app;
}
// DATABASE
var database = null;
mongoClient.connect(config.url, function(err, returnDB) {
if(err) {
console.log(err);
} else {
console.log("DB connected");
startApp(returnDB);
}
});
Legacy code that no longer works:
var mongoose = require('mongoose');
...
// Connect to DB
console.log('Connect to database (' + db.url + ')');
mongoose.connect(db.url);
I have added a callback to this connect method but it never gets called (error or no error, this connect function never gets to my callback).
This entire legacy app relies on the API using mongoose to talk to the database so I do not want to redo it all using mongodb. How can I fix this?
*config.url and db.url are loaded from the same file and it is a valid and running mongodb.
It was really easy to fix. Thanks #Bhavik for asking me what version I was using.
I updated mongoose to 4.8.1 by specifying the newest version in packages.json and the issue is resolved.
I am writing a MEAN application for work and I have come up to a roadblock. My index.js file, which contains my mongo db connection information, seems to be wrong and I am scratching my head to find the solution. Unfortunately all similar issues I see are on the 'nix side. I am not very well versed in Windows so if this is a stupid question, I apologize.
Current index.js file:
var express = require('express');
var mongoose = require('mongoose');
var bodyParser = require('body-parser');
var methodOverride = require('method-override');
var _ = require('lodash');
var dbURI = 'mongodb:127.0.0.1\d$\db\pclistapp';
// Create the app
var app = express();
// Add middleware necessayr for the REST API
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
app.use(methodOverride('X-HTTP-Method_Override'));
// Connect to MongoDB
mongoose.connect(dbURI);
//var db = mongoose.connection;
// CONNECTION EVENTS
// When successfully connected
mongoose.connection.on('connected', function () {
console.log('Mongoose default connection open to ' + dbURI);
});
// If the connection throws an error
mongoose.connection.on('error',function (err) {
console.log('Mongoose default connection error: ' + err);
});
// When the connection is disconnected
mongoose.connection.on('disconnected', function () {
console.log('Mongoose default connection disconnected');
});
// If the Node process ends, close the Mongoose connection
process.on('SIGINT', function() {
mongoose.connection.close(function () {
console.log('Mongoose default connection disconnected through app termination');
process.exit(0);
});
});
// Test connection
mongoose.connection.once('open', function() {
console.log('Listening on port 3000... ');
app.listen(3000);
})
Output when I try and run node index.js is MonogError: getaddrinfo ENOTFOUND mongodb mongodb:127. The DB is currently running on port 27017.
I have tried
mongodb:\\"PCname"\d$\db\pclistapp
mongodb:\\localhost\d$\db\pclistapp
mongodb:"PCname"\d$\db\pclistapp
mongodb:localhost\d$\db\pclistapp
and none of them seem to work. I know the UNC works for \"PCname"\d$\db\pclistapp so I am not sure what the issue is.
DB Connection Issue
DB Operational
Took a long time but the mistake was simple. I re-wrote the code to condense the errors and it's not a UNC which I need to connect to but via HTTP. Fix that and I was off to the races.
Silly me.
Code:
var mongoURI = "mongodb://localhost:27017/pclistapp";
var MongoDB = mongoose.connect(mongoURI).connection;
MongoDB.on('error', function(err) { console.log(err.message); });
MongoDB.once('open', function() {
console.log("mongodb connection open");
});
I am using the express framework and would like to connect to a mongodb without using mongoose, but with the native nodejs Mongodb driver. How can I do this without creating a new connection every time?
To handle get or post requests I currently open a new connection to the db for every request and close it on completion of the request. Is there a better way to do this? Thanks in advance.
Following the example from my comment, modifying it so that the app handles errors rather than failing to start the server.
var express = require('express');
var mongodb = require('mongodb');
var app = express();
var MongoClient = require('mongodb').MongoClient;
var dbURL = "mongodb://localhost:27017/integration_test";
var db;
// Initialize connection once
MongoClient.connect(dbURL, function(err, database) {
if(err) return console.error(err);
db = database;
// the Mongo driver recommends starting the server here
// because most apps *should* fail to start if they have no DB.
// If yours is the exception, move the server startup elsewhere.
});
// Reuse database object in request handlers
app.get("/", function(req, res, next) {
var collection = "replicaset_mongo_client_collection";
db.collection(collection).find({}, function(err, docs) {
if(err) return next(err);
docs.each(function(err, doc) {
if(doc) {
console.log(doc);
}
else {
res.end();
}
});
});
});
app.use(function(err, req, res){
// handle error here. For example, logging and
// returning a friendly error page
});
// Starting the app here will work, but some users
// will get errors if the db connection process is slow.
app.listen(3000);
console.log("Listening on port 3000");
var mongodb = require('mongodb');
var uri = 'mongodb://localhost:27017/dbname';
module.exports = function(callback) {
mongodb.MongoClient.connect(uri, callback);
};
Ad this snippet in a file say connect.js and then require this file(connect.js) in your file where you are declaring your functions for http requests.
I'd like to know how to work with connectivity to a database in MEAN stack application. In particular, when should I create a connection to a database and when should I destroy a connection to a database. Should I create and destroy a connection on every new HTTP request or should I store a once created connection and use it for any subsequent requests as long as possible. I use Mongoose as a modeling tool.
Here is an example.
This is my routes.js file with a route /index. A request to this route should fetch some date from MongoDb database. It bothers me how I connect and disconnect to a database now. Yes, I connect and disconnect to a database exactly as written in Mongoose docs, but it it the right way to do it in a serious production environment?
var express = require('express');
var router = express.Router();
var config = require('./db-config');
// I create a Mongoose instance as a module object,
// as opposite to create it in every request handler function below.
var mongoose = require('mongoose');
var productSchema = require('../db/productSchema'); // model schema is also a module-wide object
// And here is a request handler function.
// It is called on every request as a brand new.
// I create and destroy a database connection inside this request handler
router.get('/index', function(req, res, next) {
// I connect to a database on every request.
// Do I need to do it here in a request handler?
// May I do it outside of this request handler on a module-wide level?
mongoose.connect('mongodb://my_database');
// I create a new connection here in a request handler.
// So it lives only during this request handler run.
// Is this the right way? May I do it outside of this request handler
// on a module-wide level and somehow keep this connection and use it
// in every subsequent requests to this or any other route in the app?
var db = mongoose.connection;
db.on('connecting', function() {
console.log('connecting');
});
db.on('connected', function() {
console.log('connected');
});
db.on('open', function() {
console.log('open');
});
db.on('error', console.error.bind(console, 'connection error'));
db.once('open', function(cb) {
var Product = mongoose.model('Product', productSchema);
Product.find({category: "books"}, function(err, prods) {
if (err) return console.error(err);
// I close a connection here in a callback.
// As soon as successfully fetched the data.
// Do I need to close it after every request?
// What is the right place and time to do it?
db.close(disconnect);
res.json(prods);
});
});
})
Found some good answers:
https://softwareengineering.stackexchange.com/questions/142065/creating-database-connections-do-it-once-or-for-each-query
What are best practices on managing database connections in .NET?
Its best practice to have your db connection in a separate module (db.js)
var mongoose = require('mongoose')
mongoose.connect('mongodb://localhost/dbname', function(){
console.log('mongodb connected')
})
module.exports = mongoose
Each model should have a separate module that takes in the db connection (post.js)
var db = require('../db.js')
var Post = db.model('Post', {
username: {type: String, required: true},
body: {type: String, required: true},
date: { type: Date, required: true, default: Date.now }
})
module.exports = Post
Then whenever you need to use that data set just require it and make calls
var Post = require('/models/post')
Post.save()
Post.find()
This is an opinion based question I'd say. What I use for my app is
app.get('/', function (req, res) {
res.sendfile('index.html');
});
mongoose.connect('mongodb://localhost:27017/my_db');
This way I create a connection once rather than on every HTTP request. Your way should work fine but it seems you will have to connect and disconnect the db to your app way too many times specially when the app is in development.
You want your connection to act like a singleton so as mentioned in the answer above it makes sense to do it outside of, and preferable before your routes:
var compression = require('compression');
var express = require('express');
var app = express();
var port = process.env.PORT || 8080;
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var session = require('express-session');
...
app.use(compression());
// db
var mongoose = require('mongoose');
var configDB = require('./config/database.js');
mongoose.connect(configDB.url); // connect to our database
config/database.js:
module.exports = {
'url' : '#localhost:27017/dbname'
};
This is my solution :
import express from 'express';
import mongoose from 'mongoose';
import { name } from '../package.json';
import * as localconfig from './local-config';
import debug from 'debug';
debug(name);
const app = express();
const port = process.env.PORT || 3000;
const mongoUrl = localconfig.credentials.MONGO_URL;
import usersRoutes from './routes/users/user-routes';
app.use('/v1/users', usersRoutes);
mongoose.connect(mongoUrl)
.then(() => {
debug('DB connection successful');
app.listen(port, '0.0.0.0', () => {
debug(`Running on port ${port}`);
});
})
.catch((err) => {
debug(err);
});
You should first check weather the connection is successful or not and only then listen to a certain port. This is my app.js file where all the routes are loaded, so you do not have to call the db connection in all your files. You have a single config file where all the config is done. Your router file user-routes.js will look something similar to this:
import express from 'express';
import User from '../models/user'
const router = express.Router();
router.get('/', (req, res, next) => {
User.find()
.then((response) => res.json(response))
.catch((err) => next(err));
});
module.exports = router;