I can't establish a connection between MongoDB and my website on NodeJS via Mongoose - javascript

I am trying to connect my local database, which is MongoDB with my website using Mongoose, but I am receiving Error 404. What I have to do in this situation?
--the next file is controller for my model
var mongoose = require('mongoose');
var db = 'mongodb://localhost/employeers';
var Emp = require('../models/employeers');
mongoose.connect(db);
module.exports.allEmployeers=function(req,res){
console.log('getting information about everyone employeer');
Emp.find({})
.exec(function(err,employeers){
if(err){
res.send("Error has occured");
}
else{
console.log(employeers);
res.json(employeers);
}
})
};
--my route file
var ctrlEmployeers = require('../controllers/employeers');
router.get('/employeers', ctrlEmployeers.allEmployeers);
I expect when I enter localhost:3000/employeers in the browser, every employeer of my local database to be exported in JSON format. Instead of that I receive a 404 error: Page is not found.

Try this
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/employeers', { useNewUrlParser: true });
var Emp = require('../models/employeers');
module.exports.allEmployeers=function(req,res){
console.log('getting information about everyone employeer');
Emp.find({})
.exec(function(err,employeers){
if(err){
res.send("Error has occured");
}
else{
console.log(employeers);
res.json(employeers);
}
})
};

Related

Do you need to save a file locally before sending it to a mongo db?

I am learning how to upload images from my React website to my Mongo database through an express server. In every tutorial I have read, the author saves the file locally in the express server before sending it to the Mongo database. Is there a way to avoid having to store the file locally by keeping it in a local variable which is then uploaded to the database?
Here are the tutorials I am referring to:
https://www.positronx.io/react-file-upload-tutorial-with-node-express-and-multer/
https://medium.com/ecmastack/uploading-files-with-react-js-and-node-js-e7e6b707f4ef
Thank you for your help.
I guess The GridFS API would be helpful to you.It says :
you can .pipe() directly from file streams to MongoDB
Here is the sample example according to doc :
const assert = require('assert');
const fs = require('fs');
const mongodb = require('mongodb');
const uri = 'mongodb://localhost:27017';
const dbName = 'test';
mongodb.MongoClient.connect(uri, function(error, client) {
assert.ifError(error);
const db = client.db(dbName);
var bucket = new mongodb.GridFSBucket(db);
fs.createReadStream('./meistersinger.mp3').
pipe(bucket.openUploadStream('meistersinger.mp3')).
on('error', function(error) {
assert.ifError(error);
}).
on('finish', function() {
console.log('done!');
process.exit(0);
});
});
documentation link : https://mongodb.github.io/node-mongodb-native/3.0/tutorials/gridfs/streaming/
Hope this help !
yes you want to store you files locally. I used an NFS server (FreeNas) and mounted it to that local folder.
So when i saved a file to that location, it was stored on the other NFS server. Then i sent that image location as a response back to react, which then saved that location in Mongodb.
Example uploads.js
router.post('/', auth, async (req, res) => {
let CurrentDate = moment().unix();
if (req.files.file === null) {
return res.status(400).json({ msg: 'no file uploaded' });
}
let user = await User.findById(req.user.id).select('-password');
let file = req.files.file;
file.name = CurrentDate + user._id + '.jpg';
file.mv(`./client/public/uploads/${file.name}`, (err) => {
if (err) {
console.error(err);
return res.status(500).send(err);
}
res.json({ fileName: file.name, filePath: `/uploads/${file.name}`});
});
});
This is what the mongodb entry looks like
image:"/uploads/15951066675f1365239d46882312332d20.jpg"

Searching for best practice to use one mongodb connection in multiple javascript-files

At the moment, I develop a node.js REST webservice with express. I used MongoDB + Mongoose to establish a database.
Now, I have the problem, that I can only use the db connection in the file where I established the connection. I found a solution to use the connection also in other files by "module.exports" the _db variable. But I don't know, if this is the best practise. Here is my code:
databaseManager.js
// Establish a connection to the database.
mongoose.Promise = global.Promise
mongoose.connect('mongodb://'+cfg.db.ip+':'+cfg.db.port+'/'+cfg.db.name)
var _db = mongoose.connection
_db.on('error', console.error.bind(console, 'DB connection error'))
_db.once('open', function()
{
console.log("DatabaseM: Connected to the database")
})
[...]
module.exports =
{
db : _db,
}
otherFile.js
var database = require('./databaseManagement')
[...]
database.db.collection('users').findOne({ name: "ashton"}, function(err, user)
{
if (err) return callback(consts.ERROR_DB, null)
if (!user) return callback(consts.WARN_DB_NO_CLIENT)
callback(null, user)
})
It works great. But there may be a risk that I do not see?
Thanks a lot :-)
In your app.js file :
var url="mongdb:\\localhost:27017\dbname";
mongoose.connect(url); //it open default connection for mongodb and is handled by mongoose
Now perform all your task whatever you want :
mongoose.connection.on('connected', function () {
console.log('Mongoose default connection open to ' + dbURI);
});
Bring all your database model in app.js file like as such:
var model1 = require('./models/model1');
model1.js
var mongoose = require('mongoose');
var data = new mongoose.Schema({
name:{type:String, required:true}
});
module.exports = mongoose.model('collectionName', data);
Now, when all your tasks are over. Simply close default connection like this :
mongoose.connection.on('disconnected', function () {
console.log('Mongoose default connection disconnected');
});
If any error occurs in connection handle it like this :
mongoose.connection.on('error',function (err) {
console.log('Mongoose default connection error: ' + err);
});
If node service exits then close connection usig this code
process.on('SIGINT', function() {
mongoose.connection.close(function () {
console.log('Mongoose default connection disconnected through app termination');
process.exit(0);
});
});

Can two servers access a common mongoDB database

I have 2 webservers that I have created on ports 3000 and 4000.
One of the webservers created a database and has 3 collections..
show dbs
local 0.000GB
sensor_db 0.000GB
use sensor_db
switched to db sensor_db
show collections
sensors
templategroups
templates
Can the 2nd server access this Database created ? if yes, I am not able to access the collections ..Is there any syntax to it?
1st server:
var express = require('express');
var app= express();
var path = require('path');
var bodyParser= require('body-parser');
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/sensor_db');
var Schema = mongoose.Schema;
var sensorSchema = new Schema({
value:{ type:Number, default:0},
format:{type:String, default:"default"},
id:{type:Number,required:true,unique:true},
description:{type:String},
type:{type:String},
groupId:{type:Number},
users:{type:Array,default:[]},
admin:{type:String,default:'Undefined'},
status:{type:String,default:'Undefined'},
owner:{type:String,default:'Undefined'},
templateId:{type:Number}
});
var Sensor = mongoose.model('Sensor',sensorSchema);
app.get('/sensorlist',function(req,res) {
console.log("I recieved a GET /sensorlist request");
Sensor.find(function(err,data){
if (err) return console.error(err);
console.log(data);
res.json(data)
});
});
app.post('/check/health',function(req,res){
socket.emit('data', 'I need your health status', function ack(data) {
console.log('data emit was acknowledged by Monitoring Server:', data);
return res.json(data);
});
});
2nd Server:
var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
var express = require('express');
io.on('connection', function(socket){
console.log('connection received from Provisioning');
// To get messages from Provisioning server
socket.on('data', function(data, ack) {
console.log('Message from provision is : ' + ': ' + data);
ack('here is your data - 1111');
console.log("Trying to access the Sensor_DB Database");
Sensor.find(function(err,data){
if(err) return console.error(err);
console.log(data);
//res.json(data);
});
});
});
server.listen(4000, function(){
console.log('socket.io server listening on *:4000');
});
I get error - Sensor is not defined
Much Thanks
Jessi
I tried to dispay the collections once its connected to the DB but get this error message : Cannot read property 'hasListCollectionsCommand' of null
var mongoose = require('mongoose');
mongoose.connect('mongodb://127.0.0.1:27017/sensor_db') ;
console.log("successfully connected to the database");
//mongoose.connection.db
mongoose.connection.db.listCollections().toArray(function(err, names) {
if (err) {
console.log(err);
}
else {
names.forEach(function(e,i,a) {
mongoose.connection.db.dropCollection(e.name);
console.log("--->>", e.name);
});
}
});
Two Different servers cannot share the same instance of the sensor object.
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/sensor_db');
var Schema = mongoose.Schema;
var sensorSchema = new Schema({
value:{ type:Number, default:0},
format:{type:String, default:"default"},
id:{type:Number,required:true,unique:true},
description:{type:String},
type:{type:String},
groupId:{type:Number},
users:{type:Array,default:[]},
admin:{type:String,default:'Undefined'},
status:{type:String,default:'Undefined'},
owner:{type:String,default:'Undefined'},
templateId:{type:Number}
});
var Sensor = mongoose.model('Sensor',sensorSchema);
This code declaring the schema for one server not for the second . so you have to declare the instance in the second server also.
Issue not with the mongo data base issue is the sensor instance that is not have any declaration in second server.

Node.js app giving ERR_EMPTY_RESPONSE

I'm having serious issues with an app I am building with Node.js, Express, MongoDB and Mongoose. Last night everything seemed to work when I used nodemon server.js to `run the server. On the command line everything seems to be working but on the browser (in particular Chrome) I get the following error: No data received ERR_EMPTY_RESPONSE. I've tried other Node projects on my machine and they too are struggling to work. I did a npm update last night in order to update my modules because of another error I was getting from MongoDB/Mongoose { [Error: Cannot find module '../build/Release/bson'] code: 'MODULE_NOT_FOUND'}. I used the solution in this answer to try and fix it and it didn't work and I still get that error. Now I don't get any files at all being served to my browser. My code is below. Please help:
//grab express and Mongoose
var express = require('express');
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
//create an express app
var app = express();
app.use(express.static('/public/css', {"root": __dirname}));
//create a database
mongoose.connect('mongodb://localhost/__dirname');
//connect to the data store on the set up the database
var db = mongoose.connection;
//Create a model which connects to the schema and entries collection in the __dirname database
var Entry = mongoose.model("Entry", new Schema({date: 'date', link: 'string'}), "entries");
mongoose.connection.on("open", function() {
console.log("mongodb is connected!");
});
//start the server on the port 8080
app.listen(8080);
//The routes
//The route for getting data for the database
app.get("/database", function(req, res) {
Entry.find({}, function(err, data) {console.log(err, data, data.length); });
});
//The route for posting data on the database
app.post("/database", function(req, res) {
//test new post
var newMonth = new Entry({date: '1997-10-30', link: 'https://wwww.youtube.com/'});
newMonth.save(function(err) {
if (err !== null) {
//object was not save
console.log(err);
} else {
console.log("it was saved!")
};
});
});
//create an express route for the home page at http://localhost:8080/
app.get('/', function(req, res) {
res.send('ok');
res.sendFile('/views/index.html', {"root": __dirname + ''});
});
//Send a message to the console
console.log('The server has started');
//The route for getting data for the database
app.get("/database", function(req, res) {
Entry.find({}, function(err, data) {console.log(err, data, data.length); });
});
//The route for posting data on the database
app.post("/database", function(req, res) {
//test new post
var newMonth = new Entry({date: '1997-10-30', link: 'https://wwww.youtube.com/'});
newMonth.save(function(err) {
if (err !== null) {
//object was not save
console.log(err);
} else {
console.log("it was saved!")
};
});
});
These routes don't send anything back to the client via res. The bson error isn't a big deal - it's just telling you it can't use the C++ bson parser and instead is using the native JS one.
A fix could be:
//The route for getting data for the database
app.get("/database", function(req, res) {
Entry.find({}, function(err, data) {
if (err) {
res.status(404).json({"error":"not found","err":err});
return;
}
res.json(data);
});
});
//The route for posting data on the database
app.post("/database", function(req, res) {
//test new post
var newMonth = new Entry({date: '1997-10-30', link: 'https://wwww.youtube.com/'});
newMonth.save(function(err) {
if (err !== null) {
res.status(500).json({ error: "save failed", err: err});
return;
} else {
res.status(201).json(newMonth);
};
});
});
updated june 2020
ERR_EMPTY_RESPONSE express js
package.json
"cors": "^2.8.4",
"csurf": "^1.9.0",
"express": "^4.15.4",
this error show when you try to access with the wrong HTTP request. check first your request was correct
maybe your cors parameter wrong

How do I use node-mongodb-native to connect to Heroku?

I'm getting really confused over how to connect to MongoLab on Heroku.
To connect using the uri to Heroku, I was trying to follow this example:
http://experiencecraftsmanship.wordpress.com/2012/01/06/heroku-node-js-mongodb-featuring-the-native-driver/
I looked at both his web.js and deep.js.
They both do something like:
connect.createServer(
require( 'connect-jsonrpc' )( contacts )
).listen( port );
But then only the database query in 'contacts' get passed into this server then?
Am I allowed to do multiple connect.createServer for each of my database access method?
The following is part of my code when just connecting to MongoDB locally. I am unsure of how to modify it to connect to MongoLab on Heroku.
Can someone teach me how to modify my code to connect? Or explain some of these concepts? I have no idea why the author of that website I posted used so many callbacks to do a database call, when my approach below seems straightforward enough (I'm new to JavaScript, not good with callbacks).
var app = module.exports = express.createServer(
form({ keepExtensions: true })
);
var Db = require('mongodb').Db;
var Server = require('mongodb').Server;
var client = new Db('blog', new Server('127.0.0.1', 27017, {}));
var posts;
var getAllPosts = function(err, collection) {
collection.find().toArray(function(err, results) {
posts = results;
console.log(results);
client.close();
});
}
app.get('/', function(req, response) {
client.open(function(err, pClient) {
client.collection('posts', getAllPosts);
});
// some code
response.render('layout', { posts: posts, title: 'Raymond', contentPage: 'blog' });
});
You connect to your mongolab database (so you can't create a new "blog" database). process.env.MONGOLAB_URI includes the database name as well. See your mongolab uri:
heroku config | grep MONGOLAB_URI
It looks like: mongodb://heroku_app123456:password#dbh73.mongolab.com:27737/heroku_app123456
On github there is an example how to connect and retrieve data from a mongolab database.
Use "connect" to connect to mongo, instead of defining db, server, client:
var connect = require('connect');
var mongo = require('mongodb');
var database = null;
var mongostr = [YOUR MONGOLAB_URI];
mongo.connect(mongostr, {}, function(error, db)
{
console.log("connected, db: " + db);
database = db;
database.addListener("error", function(error){
console.log("Error connecting to MongoLab");
});
});

Categories