why mongodb doesnt connect with my nodejs simple application? - node.js

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

Related

NodeJS connection with MongoDB using Mongoose

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

Mongoose unable to save or persist to database with a POST Request; gives no error

I am trying to send data through Postman to a REST API made of Node.js and Mongoose
I am getting the following response :
but this does not persist or save to Mongo DB :
I added the following :
mongoose.set("debug", (collectionName, method, query, doc) => {
console.log(`${collectionName}.${method}`, JSON.stringify(query), doc);
});
so I am also getting this at the console (is session supposed to be null)?:
standups.insertOne {"_id":"5f9e54cea6d454065f0a963b","teamMember":"Mark","project":"Trinity Web Application","workYesterday":"Build out the Models","workToday":"Testing the API Endpoint using Postman","impediment":"None","createdOn":"2020-10-31T22:30:03.000Z","__v":0} { session: null }
I have configured with the following files at my server backend :
api/routes/standup.js
const Standup = require('../../models/standup')
module.exports = function (router) {
// GET: the 12 newest stand-up meeting notes
router.get('/standup', function (req, res) {
})
// POST: Get new meeting note document...
router.post('/standup', async function (req, res) {
let note = new Standup(req.body)
await note.save(function (err, note) {
if (err) {
return res.status(400).json(err)
}
res.status(200).json(note)
})
})
}
api/models/standup.js
const mongoose = require('mongoose')
const standupSchema = new mongoose.Schema({
teamMember: { type: String },
project: { type: String },
workYesterday: { type: String },
workToday: { type: String },
impediment: { type: String },
createdOn: { type: Date, default: Date.now }
}, { bufferCommands: false })
module.exports = mongoose.model('Standup', standupSchema)
app.js
const express = require('express')
const app = express()
const api = require('./api')
const morgan = require('morgan')
const bodyParser = require('body-parser')
const cors = require('cors')
const port = process.env.PORT || 8081
app.set('port', port)
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({extended: false}))
app.use(cors())
app.use('/api', api)
app.use(express.static('static'))
app.use(morgan('dev'))
app.use(function (req,res) {
const err = new Error('Not Found')
err.status = 404
res.json(err)
})
const mongoose = require('mongoose')
mongoose.connect('mongodb://127.0.0.1:27017/virtualstandups', {useNewUrlParser: true, bufferCommands: false})
mongoose.set("debug", (collectionName, method, query, doc) => {
console.log(`${collectionName}.${method}`, JSON.stringify(query), doc);
});
const db = mongoose.connection
db.on('error', console.error.bind(console, 'connection error: '))
db.once('open', function() {
console.log('Connected to MongoDB')
app.listen(port, function() {
console.log('API Server Listening on port ' + app.get('port') + '!')
})
})
Backend does return original object; however does not persist and sends no error. I am using MongoDB and Node through WSL2.
Ok, my problem was
I installed Mongo DB as a service on windows
I installed mongodb on WSL2 / Ubuntu at a different time ( I forgot I already installed on windows)
Both using the same port 27107
Using Mongo DB Compass, I can only see the Windows MongoDB which yielded no changes; but data was actually getting sent to the WSL2/Ubuntu MongoDB.
Solution :
Uninstall MongoDB on Windows or run MongoDB in only one platform.

How to Update data from Node.js

I want to update my data by using id but all the time i am not able to update it. It is even not giving any error and storing null values
router.put('/special/:id', function(req, res) {
User.findByIdAndUpdate(req.params.id, {
$set: {email: req.body.email, password: req.body.password}
},
{
new: true,
useFindAndModify: false
},
function(err, updatedData) {
if(err) {
res.send('Error updating');
} else {
res.json(updatedData);
}
});
});
Try rewriting it using async, and make sure your Mongoose schema is correct as well.
So your mongoose model should be a seperate file called 'userModel.js'.
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var userSchema = new Schema ({
email: String,
password: String,
});
let User = module.exports = mongoose.model('User', userSchema);
Then in your app.js.
Have:
const express = require('express');
const app = express();
const mongoose = require('mongoose');
const port = 3000;
const bodyParser = require('body-parser');
//Body Parser Middleware
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))
// parse application/json
app.use(bodyParser.json())
//connect to db
mongoose.connect('mongodb://localhost:27017/YOUR_DB_NAME_HERE',{useNewUrlParser: true})
let db = mongoose.connection;
//check db connection
db.once('open', function() {
console.log('Connected to ' + db.name)
})
//check for db error
db.on('error', function(err) {
console.log(err);
})
//Starting App (on localhost:3000)
app.listen(port, function() {
console.log('Server started on port ' + port);
});
Note: Once you start the app. In your node console if you are not seeing a message saying 'Connected to {YOUR DB NAME}'. Then either you don't have mongoDB running or you don't have it installed. So first you want to make a new console window and type:
mongod
This should work, and if its already running you should see a message at the bottom saying:
2019-07-19T12:17:37.716+1000 E STORAGE [initandlisten] Failed to set up listener: SocketException: Address already in use
Now once you figure this out. And you've found that your connection to mongoDB is good. You want to redo your PUT route to make an async request as follows.
Note: Before the route, you need to require your model so mongoose can update records for you.
//Requiring your shop model
const User = require('./models/userModel')
app.put('/special/:id', async function(req, res){
const id = req.params.id
//Making a user object to parse to the update function
let updatedUser = {}
updatedUser.email = req.body.email
updatedUser.password = req.body.password
await User.findByIdAndUpdate(id, updatedUser, function(err, updatedData){
if(err){
console.log(err)
}
else {
console.log(updatedData)
//res.redirect or res.send whatever you want to do
}
})
})

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