NodeJS connection with MongoDB using Mongoose - node.js

I am trying to view mongodb collections (just to view) in browser URL by accessing localhost:4000/books
app.js code:
var express = require("express");
var app = express();
var bodyParser = require("body-parser");
var mongoose = require("mongoose");
var Book = require("./book.model");
//mongo DB database connection: databse nmae is: example
var db = "mongodb://localhost:27017/example";
mongoose.connect(db, { useNewUrlParser: true, useUnifiedTopology: true });
const conSuccess = mongoose.connection
conSuccess.once('open', _ => {
console.log('Database connected:', db)
})
conSuccess.on('error', err => {
console.error('connection error:', err)
})
var port = 4000;
app.listen(port, function () {
console.log("app listening on port " + port);
});
//REST get
app.get('/', function(req,res){
res.send("happy to be here");
});
//work on here localhost:4000 works but not localhost?4000/books
//get all "books" collections
app.get('/books', function(req,res) {
console.log("get all books");
Book.find({})
exec(function(err, books){
if(err){
res.send("error has occured");
} else {
console.log(books);
res.json(books);
}
});
});
book.model.js
var mongoose = require("mongoose");
var Schema = mongoose.Schema;
var BookSchema = new Schema({
title: String,
author: String,
category: String,
});
module.exports = mongoose.model("Book", BookSchema);
and the mongodb server started in cmd propt
ran> node app
console displayed messages as
"app listening on port 4000
Database connected: mongodb://localhost:27017/example"
in URL, when I tried to access like this
localhost:4000/books
display error as
reference error: exec is not defined. why is that, please help on this issue. I am working on rectify this erro for 3 days and really stcuk on this without moving forward.

use . before exec just try like this
app.get('/books', function(req,res) {
console.log("get all books");
Book.find({}).exec(function(err, books){
if(err){
res.send("error has occured");
} else {
console.log(books);
res.json(books);
}
});
});

Related

Can't insert on MongoDB

I'm new at using back-end code.
I'm trying to Insert basic line into MongoDB online DB.
These are my files:
server.js:
const express = require('express');
const MongoClient = require('mongodb').MongoClient;
const bodyParser = require('body-parser');
const app = express();
var db = require('./config/db');
const port = 8000;
app.use(bodyParser.urlencoded({ extended: true }));
MongoClient.connect(db.url, (err, database) => {
if (err) return console.log(err);
db = database.db('note-api');
require('./app/routes')(app, db);
require('./app/routes')(app, database);
app.listen(port, () => {
console.log('We are live on ' + port);
});
})
note_routes.js:
module.exports = function (app, db) {
// const collection =
app.post('/notes', (req, res) => {
const note = { text: req.body.body, title: req.body.title };
db.collection('notes').insert(note, (err, result) => {
if (err) {
res.send({ 'error': err });
} else {
res.send(result.ops[0]);
}
});
});
};
db.js:
module.exports = {
url: "mongodb://laelav:laelav1#ds227594.mlab.com:27594/getremp"
};
Whenever i try using POST and wish to update the online DB - I get an unauthorized error:
unauthorized error
Then I added this line in note_routes.js:
db.grantRolesToUser("laelav", [{ role: "readWrite", db: "getremp" }]);
And got the following "TypeError: db.grantRolesToUser is not a function":
not a function error
Please help!

Creating MongoDB connection with mongoose

I am desperately trying to create a connection with mongoDB with the MEAN stack, using mongoose.
My MongoDB instance (mongod) is running and I can use mongo.exe and tested it by inserting some documents, it worked fine. But I have problems to create a connection to MongoDB with mongoose, and inserting a document with the .save() method does not work either...
I first wanted to try my POST method, created a function and tested it by creating some values in POSTMAN. But no documents were inserted in my MongoDB datbase..
This is my app.js file:
var express = require('express');
var app = express();
var bodyParser = require("body-parser");
var morgan = require("morgan");
//var routes = require('./routes');
//var cors = require('cors')
//configure app
app.use(morgan('dev')); //log requests to the console
//configure body parser
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
var port = process.env.PORT || 5000;
//DATABASE SETUP
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/DNZ'); //connect to uor datbaase
//Handle the connection event
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
console.log("DB connection alive");
});
//DNZ models live here
var FA = require('./models/DNZmodels/FA');
//ROUTES FOR OUR API
//=============================================================================
//create our router
var router = express.Router();
//middleware to use for all requests
router.use(function(req, res, next) {
// do logging
console.log('Something is happening.');
console.log('Today is:', Date())
next();
});
//test route to make sure everything is working (accessed at GET http://localhost:5000/DNZ/)
router.get('/', function(req, res) {
res.json({ message: 'Welcome to DNZ API!' });
});
//on routes that end in /FA
//----------------------------------------------------
router.route('/FA')
// create a FA (accessed at POST http://localhost:8080/DNZ/FA)
.post(function(req, res) {
//console.log(req.body);
//console.log(req.body.params);
//res.setHeader('Content-Type', 'application/json')
res.send(JSON.stringify(req.body));
/*
var timestamp = req.body.Timestamp;
var prognostizierterBetriebswert = req.body.PrognostizierterBetriebswert;
var posFlexPot = req.body.posFlexPot;
var negFlexPot = req.body.negFlexPot;
var leistungsuntergrenze = req.body.Leistungsuntergrenze;
var leistungsobergrenze = req.body.Leistungsobergrenze;
var posGesEnergie = req.body.posGesEnergie;
var negGesEnergie = req.body.negGesEnergie;
var preissignal = req.body.Preissignal;
var dummy1 = req.body.Dummy1;
var dummy2 = req.body.Dummy2;
var dummy3 = req.body.Dummy3;
*/
var fa = new FA();
fa.name = req.body.name;
console.log("Hier erscheint var fa:", fa);
//console.log(Dummy1);
//res.send(JSON.stringify(timestamp));
// create a new instance of the FA model
/*
var fa = new FA({
Timestamp: timestamp,
Leistungsuntergrenze: leistungsuntergrenze,
Leistungsobergrenze:leistungsobergrenze,
PrognostizierterBetriebswert :prognostizierterBetriebswert,
posFlexPot: posFlexPot,
negFlexPot:negFlexPot,
posGesEnergie: posGesEnergie,
negGesEnergie: negGesEnergie,
Preissignal:preissignal,
Dummy1: dummy1,
Dummy2: dummy2,
Dummy3: dummy3
})
*/
//SAVE the new instance
fa.save(function(err) {
if (err) {
console.log(err);
res.status(400);
res.send(err);
}
else {
console.log("debug");
res.status(200);
res.json({ message: 'FA created!' });
}
});
})
// get all the FAs (accessed at GET http://localhost:8080/DNZ/FA)
.get(function(req, res) {
FA.find(function(err, fas) {
if (err)
res.send(err);
res.json(fas);
});
});
//on routes that end in /FA/:FA_id
//----------------------------------------------------
router.route('/FA/:FA_id')
// get the bear with that id
.get(function(req, res) {
FA.findById(req.params.bear_id, function(err, fa) {
if (err)
res.send(err);
res.json(fa);
});
})
// update the bear with this id
.put(function(req, res) {
FA.findById(req.params.FA_id, function(err, fa) {
if (err)
res.send(fa);
//bear.name = req.body.name;
/*
FA.save(function(err) {
if (err)
res.send(err);
res.json({ message: 'FA updated!' });
});
*/
});
})
/*
// delete the bear with this id
.delete(function(req, res) {
FA.remove({
_id: req.params.bear_id
}, function(err, FA) {
if (err)
res.send(err);
res.json({ message: 'Successfully deleted' });
});
});
*/
//REGISTER OUR ROUTES -------------------------------
app.use('/DNZ', router);
//START THE SERVER
//=============================================================================
app.listen(port);
console.log('Magic happens on port ' + port);
/*
// set static directories
app.use(express.static('./dist'));
app.use(cors());
// Define Routes
var index = require('./routes/index');
var users = require('./routes/users');
//Set up routes
routes.init(app)
//run
app.listen(port);*/
console.log('Server started, Listening on port ', port);
I used the "template" from the Bear tutorial:
https://scotch.io/tutorials/build-a-restful-api-using-node-and-express-4
the problem here is already, that there is no message: "DB connection alive". However, in the bear tutorial (whose code I used here), the DB connection is built and I can insert bear documents in the database. However, here it does not work...
and this is my FA Schema model from FA.js:
var mongoose = require("mongoose");
var Schema = mongoose.Schema;
var FASchema = new Schema({
Timestamp: Date,
PrognostizierterBetriebswert: Number,
posFlexPot: Number,
negFlexPot: Number,
Leistungsuntergrenze: Number,
Leistungsobergrenze: Number,
posGesEnergie: Number,
negGesEnergie: Number,
Preissignal: Number,
Dummy1: Schema.Types.Mixed,
Dummy2: Schema.Types.Mixed,
Dummy3: Schema.Types.Mixed
//same: Dummy: {}
});
//var FASchema = new Schema({name: String});
module.exports = mongoose.model("FA", FASchema, 'FA');
console.log("FA wird ausgeführt!");
Anybody got an idea why there is no DB connection created?
when I test your code , the Error (Can't set headers after they are sent) was thrown. you can delete res.send(JSON.stringify(req.body)); and restart service

why mongodb doesnt connect with my nodejs simple application?

I am trying to connect mongodb to my express nodejs web application. I am fresh new to nodejs. I am following this tutorial video https://www.youtube.com/watch?v=eB9Fq9I5ocs but I couldn't complete it due to the connection of mongodb.
the app.js code I have:
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
Genre = require('./models/genre');
mongoose.connect('mongodb://localhost/bookstore');
mongoose.connection.on('error', (err) => {
console.error('mongodb connection error', err);
});
mongoose.connection.on('connected', () => {
console.info(`Connected to mongodb`);
});
mongoose.connection.on('disconnected', () => {
console.info('Disconnected from mongodb');
});
// var mongoose = connect('mongodb://localhost/bookstore');
// var db = mongoose.connection;
app.get('/', function(req, res){
res.send('Hello World');
});
app.get('api/genres', function(req , res){
Genre.getGenres(function(err, genres){
if(err){
throw err;
}
res.json(genres);
})
});
app.listen(3666);
console.log('Server Running On http://localhost:3666');
and this is the genre.js
var mongoose = require('mongoose');
var genreSchema = mongoose.Schema({
name:{
type: String,
requires: true
},
create_date:{
type: Date,
default: Date.now
}
});
var Genre = module.exports = mongoose.model('Genre', genreSchema);
module.exports.getGenres = function(callback, limit){
Genre.find(callback).limit(limit);
}
and this is a picture of the database in the terminal
The Error that I got:
I know this is a basic question but I couldnt figured out I check on google there are others way to connect to the database but I need to know why this particular way which I just followed from the tutorial video havent worked.
As you noticed I am a new to nodejs web development so if you could suggest websites or youtube channels to get me start it I would appreciate it.
Instead of undefined connect function you should use mongoose.connect(...):
mongoose.connect('mongodb://localhost/bookstore');
But this function is deprecated, you could silence the warning, setting { useMongoClient: true } in options, but it's not recommended.
The best way is to use mongoose.connection object and its openUri method:
let conn = mongoose.connection;
conn.openUri('mongodb://localhost/bookstore');
conn.on('error', err => console.error('mongodb connection error', err));
conn.on('connected', () => console.info(`Connected to mongodb`));
conn.on('disconnected', () => console.info('Disconnected from mongodb'));

my post request using nodejs express to mongodb database doesn't work strangely?

I am trying to post data to the sever to be save into mongodb. Notice get request is working right but I couldnt post any data to mongodb database.
The main code:
// Tools to be used in the web development
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
app.use(bodyParser.json());
Genre = require('./models/genre.js');
Book = require('./models/book.js');
let conn = mongoose.connection;
conn.openUri('mongodb://localhost/bookstore');
conn.on('error', err => console.error('mongodb connection error',
err));
conn.on('connected', () => console.info(`Connected to mongodb`));
conn.on('disconnected', () => console.info('Disconnected from
mongodb'));
// Routing to specific pages:
app.get('/', function(req, res){
res.send('Hello World');
});
app.get('/api/genres', function(req , res){
Genre.getGenres(function(err, genres){
if(err){
throw err;
}
res.json(genres);
})
});
app.post('/api/genres', function(req , res){
var genre = req.body;
Genre.addGenre(genre, function(err, genre){
if(err){
throw err;
}
res.json(genre);
})
});
app.get('/api/books', function(req , res){
Book.getBooks(function(err, books){
if(err){
throw err;
}
res.json(books);
})
});
app.get('/api/books/:_id', function(req , res){
Book.getBookById(req.params._id, function(err, book){
if(err){
throw err;
}
res.json(book);
})
});
//Specify the listening port
app.listen(3666);
//Display the url on the termianl
console.log('Server Running On http://localhost:3666');
Genres
var mongoose = require('mongoose');
var genreSchema = mongoose.Schema({
name:{
type: String,
requires: true
},
create_date:{
type: Date,
default: Date.now
}
});
var Genre = module.exports = mongoose.model('Genre', genreSchema);
module.exports.getGenres = function(callback, limit){
Genre.find(callback).limit(limit);
}
//add genre
module.exports.addGenre = function(genre, callback){
Genre.create(callback);
}
I post using postman app and once I press post I receive nothing and nothing be added to the database
Postman Procedure
Postman Procedure
and The database before and after the post procedure remain the same
enter image description here
Try this instead:
module.exports.addGenre = function(genre, callback){
Genre.create(genre, callback); // genre is object to be added, { name: "Name" } for example
}

When I use mongoose & connect MongoDB, I can insert and get data. But unable to find data using MongoClient

My code as follows. Open localhost/users/,brower return
{"_id":"55519446e063d4c409f93f00","username":"justnode","__v":0}
but when I open mongo shell and input: use student and db.student.find(),I can't find anything. My MongoDB version is 3.0.1 and nodejs version is 0.12.2, OS is Centos 6.4
var express = require('express');
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var app = express();
mongoose.connect('mongodb://localhost/student', function (error) {
if (error) {
console.log(error);
}
});
var Schema = mongoose.Schema;
var UserSchema = new Schema({
username: {type: String, unique: true}
});
var UserModel = mongoose.model('UserModel', UserSchema);
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
/*
post content as follows
{
"username": "justnode"
}
*/
app.post('/users/create', function (req, res) {
console.log("in /users/create");
var userModelJson = req.body;
var userModel = new UserModel(userModelJson);
userModel.save(function(error) {
if(error) {
console.log(error);
return res.json({msg: "error"});
}
console.log("user created: " + userModel.username);
res.json(userModel);
});
});
/*
open localhost/users/ brower return {"_id":"55519446e063d4c409f93f00","username":"justnode","__v":0}]
but when I open mongo client: db.student.find() i can't find anything
*/
app.get('/users', function (req, res) {
UserModel.find({}, function (err, docs) {
res.json(docs);
});
});
var serverApp = app.listen(80, function () {
console.log('Express server listening on port ' + serverApp.address().port);
});
Change database(student), schema(UserSchema) and model(UserModel)'s name and try it again. My case, after changing the variable's name and restart, it works. (I've no idea why, maybe mongoose or mongo shell has some bug?)

Resources