How to retrieve data from mongodb - node.js

I am unable to retrieve data from mongodb.
Problem is: the code Article.find({}); is not working to retrieve data from database.
I am using WebStorm IDE. I want to retrieve all the data from data base.
Please help me to find the error in my code.
database.js
module.exports = {
database:'mongodb://localhost:27017/shopping_site',
}
models/article.js
let mongoose = require('mongoose');
// Article Schema
let articleSchema = mongoose.Schema({
title:{
type: String,
required: true
},
author:{
type: String,
required: true
},
body:{
type: String,
required: true
}
});
let Article = module.exports = mongoose.model('Article', articleSchema);
index.pug
extends layout
block content
h1 #{title}
ul.list-group
each article, i in articles
li.list-group-item= article.title
app.js
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var mongoose = require('mongoose');
var config = require('./config/database');
var bodyParser = require('body-parser');
var app = express();
// Bring in Models
let Article = require('./models/article');
//database connectionkjvhgc
mongoose.connect(config.database);
let db = mongoose.connection;
// Check connection
db.once('open', function(){
console.log('Connected to MongoDB');
});
// Check for DB errors
db.on('error', function(err){
console.log(err);
});
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
// Home Route
app.get('/', function(req, res){
Article.find({}, function(err, articles){
if(err){
console.log(err);
} else {
res.render('index', {
title:'Articles',
articles: articles
});
}
});
});
//set routes
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
//body-parser
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))
// parse application/json
app.use(bodyParser.json())
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;

move database connection code into db.js and import same in article.js
db.js
let uristring = <your connection string or import database.js>;
mongoose.connect(uristring);
// When successfully connected
mongoose.connection.on('connected', function() {
console.log('Mongoose connection open to cluster');
});
// If the connection throws an error
mongoose.connection.on('error', function(err) {
console.log('Mongoose connection error: ' + err);
});
// When the connection is disconnected
mongoose.connection.on('disconnected', function() {
console.log('Mongoose connection disconnected');
});
// When the connection is open
mongoose.connection.on('open', function() {
console.log('Mongoose connection is open');
});
module.exports = mongoose;
then in article.js
const mongoose = require('mongoose');
require('../db');

First lets bring in your model,
require('./models/article');
the create a variable for the model
const Article = mongoose.model('Article');
Next to display your articles from db
app.get('/', (req, res) => {
Article.find({}).then(Article => {
res.render('index', {Article:Article});
}).catch(err => console.log(err));
});
I hope this helps

Related

When I did res.json (newschema), the properties are not displayed anymore on Postman

When I did res.json (newschema) on post action, the properties are not displayed any more on Postman and also in Mongodb.
This is formations.routes
const express = require('express');
const router = express.Router();
const Formation = require('../models/formations');
const mongoose = require('mongoose');
const config = require('../config/database');
router.get('/', function(req, res){
//Formation.getFormations(function(err, formations){
// if(err)throw err;
// res.json(formations);
//});
Formation.find({})
.exec(function(err, Formations){
if(err){
console.log('error');
}else{
res.json(Formations);
}
})
});
router.post('/', function(req, res){
console.log('post a formations');
var newFormation = new Formation();
newFormation.title = req.body.title;
newFormation.url = req.body.url;
newFormation.description = req.body.description;
newFormation.save(function(err, newFormation){
if(err){
console.log('error insertion');
} else {
res.json(newFormation);
//res.json({success: true, msg:'user registred'});
}
});
});
This is formation.models
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const config = require('../config/database');
const FormationSchema = mongoose.Schema ({
title: String,
url: String,
description: String
});
module.exports = mongoose.model('Formation', FormationSchema, 'Formations');
This is my app.js ( endpoint)
const express = require('express');
const path = require('path');
const bodyParser = require('body-parser');
const cors = require('cors');
const passport = require('passport');
const mongoose = require('mongoose');
const config = require('./config/database');
const User = require('./models/user');
const Formation = require('./models/formations');
mongoose.connect(config.database , { useNewUrlParser: true });
mongoose.connection.on('connected', () => {
console.log('connected to database... ' + config.database);
});
mongoose.connection.on('error', (err) => {
console.log('database error'+err);
});
/*mongoose.connect('mongodb://localhost:27017/hello', { useNewUrlParser: true });
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
console.log('we are connected!');
});*/
const app = express();
const users = require('./routes/users');
const formations = require('./routes/formations');
//port number
const port = 3001;
//cors middleware
app.use(cors({
origin: 'http://localhost:4200'
}));
//passwport middelware
app.use(passport.initialize());
app.use(passport.session());
require('./config/passport')(passport); //pour implémenter fichier passport.js
//set static folder
app.use(express.static(path.join(__dirname + '/public')));
//BodyParser middleware
app.use(express.json());
app.use(bodyParser.json());
app.use('/users', users);//hedhiya ki nekteb /users barka f url yemchili direct lel const users = require('./routes/users'); fichier hedhka
app.use('/formations', formations);
//c un route
//just meloul 7atineha bch ntastiw beha
//index route
app.get('/', function(req, res){
res.send('invalid endpoint');
});
//start Server
app.use(bodyParser.urlencoded({extended:true}));
app.listen(port, () => {
console.log('Server started on port' +port);
});
And this is how I make a post action in Postman
The save method only has an error parameter in the callback. You are adding a newFormations parameter which will always be undefined and in the scope of the method you are returning undefined in the res.json call. To fix it remove the newFormation parameter as below:
newFormation.save(function(err){
if(err){
console.log('error insertion');
} else {
res.json(newFormation);
//res.json({success: true, msg:'user registred'});
}
});

socket.io not loading on heroku

I'm using node.js, express, socket.io, mongodb, mongoose, mongolab and heroku to build simple chat.
Everything work great on the localhost (without heroku), but when I deploy my app on the heroku the socket.io.js not loading.
https://prnt.sc/gm6fz0
I've read about 10-20 other similiar questions and tried other variations, but socket.io.js still won't load.
app.js - server side
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var app = require('express')();
var server = require('http').createServer(app);
var io = require('socket.io')(server);
var mongoose = require('mongoose');
var mongodb = require('mongodb');
server.listen(8080);
var uri = 'mongodb://username:password#ds141264.mlab.com:41264/chat';
var index = require('./routes/index');
var users = require('./routes/users');
mongoose.connect(uri, function(err){
if(err) {
console.log(err);
} else {
console.log('connected to mongo db');
}
});
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function callback () {
var chatSchema = mongoose.Schema ({
msg: String,
created: {type: String, default: function(){return new Date()}}
});
var Chat = mongoose.model('Message', chatSchema);
io.on('connection', function(socket){
console.log('a user connected');
var query = Chat.find({});
query.sort({'_id': -1}).limit(10).exec(function(err, docs){
if (err) throw err;
console.log('sending old msgs');
socket.emit('load old msgs', docs);
});
socket.on('disconnect', function(){
console.log('user disconnected');
});
socket.on('chat', function(msg){
console.log('message: ' + msg);
var newMsg = new Chat({ msg: msg });
newMsg.save(function(err){
if(err) throw err;
io.emit('chat', msg);
});
});
});
});
app.use(express.static(__dirname + '/public'));
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', index);
app.use('/users', users);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
global.js - client-side
var socket = io.connect();
$('#send-message-btn').click(function () {
var msg = $('#message-box').val();
socket.emit('chat', msg);
$('#message-box').val('');
return false;
});
socket.on('chat', function (msg) {
var dadd = new Date;
$('#messages').append($('<time>').text(dadd));
$('#messages').append($('<p>').text(msg));
});
socket.on('load old msgs', function(docs){
for(var i=0; i < docs.length; i++) {
$('#messages').prepend($('<p>').text(docs[i].msg));
$('#messages').prepend($('<time>').text(docs[i].created));
}
});
As Per the documentation provided on heroku (Apps using Socket.io should enable session affinity. If you plan to use node’s Cluster module or to scale your app to multiple dynos, you should also follow Socket.io’s multiple-nodes instructions.), You Basically have to execute the following command from you project directory.
heroku features:enable http-session-affinity
Best,
Daksh Miglani

NodeJS routing to 404 instead of correct page

I have the following code. I am trying to get it to show the users in my db when I go to http://localhost:4000/user, however all I get is 404. I would appreciate some help as I'm clearly not understanding something.
app.js
var express = require('express');
var path = require('path');
var logger = require('morgan');
var index = require('./routes/index');
var user = require('./routes/users');
var mongoose = require('mongoose');
var app = express();
//This is all setup code.
// view engine setup
app.set('view engine','ejs')
app.set('views', path.join(__dirname, 'views'));
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', index);
app.use('/user',user);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
// render the error page
res.status(err.status || 500);
res.render('error');
});
//Mongo code
mongoose.Promise = global.Promise;
mongoose.connect('mongodb://localhost/db1')
.then(() => console.log('Connected to db succesfully'))
.catch((err) => console.error(err));
module.exports = app;
app.listen(4000, function () {
console.log('listening on port 4000!')
})
routes/user.js
var express = require('express');
var router = express.Router();
var userModel = require('../models/users.js');
/* GET home page. */
router.get('/user', function(req, res, next) {
console.log("get request made");
});
router.route('/user')
.get(function(req, res) {
User.find(function(err, bears) {
if (err)
res.send(err);
res.json(bears);
});
});
.post(function(req, res) {
var user = new User(); // create a new instance of the Bear model
user.firstNamename = req.body.firstName; // set the bears name (comes from the request)
user.lastName=req.body.lastName;
user.email=req.body.email;
user.save(function(err) {
if (err)
res.send(err);
console.log("User created");
});
})
module.exports = router;
model/users.js
var mongoose = require('mongoose');
// Create a user schema
var userSchema = new mongoose.Schema({
firstName: String,
lastName: String,
email: String,
});
module.exports = mongoose.model('User', userSchema);
Three problems here:
first you've required ./routes/users but your route file is user.js, so it should be:
var user = require('./routes/user');
second, when you have mounted user middleware on your app you choose to prepend /user to all of user routes(app.use('/user', user);); so when you say:
router.route('/user').get(function ...
it responds to /user/user routes. so the right implementation is:
router.route('/').get(function ...
this responds to /user
third, semicolon before your post request should be removed.
Note that router.route('/').get(function... is exactly the same as router.get('/', function ... . we use first pattern for chaining different http verbs to one route. but semicolon destroyed the linking:
router
.route('/')
.get(function ...)
.post(function ...)
.delete(function ...);

HTTP post request parameters doesn't change default values of Mongoose schema

I created two Mongoose schemas and want to test them with Postman.
When I send a post HTTP request my parameters doesn't change the default value from the AnimalSchema nor does at StorySchema.
var mongoose = require('mongoose');
var AnimalSchema = new mongoose.Schema({
name: {type : String, default: ""},
audio: {type : String, default: ""},
image: {type : String, default: ""}
});
mongoose.model('Animal', AnimalSchema);
var mongoose = require('mongoose');
var express = require('express');
var router = express.Router();
var Animal = mongoose.model('Animal');
var Story = mongoose.model('Story');
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
router.get('/animals', function(req, res, next){
Animal.find(function(err, animals){
if(err){
return next(err);
}
res.json(animals);
});
});
router.post('/animals', function(req, res, next){
var animal = new Animal(req.body);
animal.save(function(err,animal){
if(err){return next(err);}
res.json(animal);
});
});
router.get('/stories', function(req, res, next){
Story.find(function(err, stories){
if(err){return next(err);}
res.json(stories);
});
});
router.post('/stories', function(req, res, next){
var story = new Story(req.body);
story.save(function(err, story){
if(err){return next(err);}
res.json(story)
});
});
module.exports = router;
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var app = express();
var mongoose = require('mongoose');
// connect MongoDB
mongoose.connect('mongodb://localhost/stuckyToys', function(err,db){
if (!err){
console.log('Connected to /stuckyToys!');
} else{
console.dir(err); //failed to connect
}
});
require('./models/Animals');
require('./models/Stories');
var routes = require('./routes/index');
var users = require('./routes/users');
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', routes);
app.use('/users', users);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
I think I made an error in my app.js file. But not sure where it is.
Anyone knows what I did wrong?
I would do something like
{*(Model)}.findById(id, function(err, animal) {
if (err) console.log(err);
{update new values here in animal with the ones you are receiving in the request}
animal.save(function(err) {
if (err) console.log(err);
});
});

Error connecting to mongolab using node.js and mongoose

I'm trying to write an API using mongoose and mongolab.
Here is my code :
./index.js
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
mongoose.connect('mongodb://user:pass#****.mlab.com:*****/****');
var Bear = require('./app/models/bear');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
var port = process.env.PORT || 8080;
var router = express.Router();
router.use(function(req, res, next){
console.log('request called');
next();
});
router.get('/', function(req, res) {
res.json({ message: 'in /' });
});
router.route('/bears')
.post(function(req, res) {
var bear = new Bear();
bear.name = req.body.name;
console.log(bear.name);
bear.save(function(err) {
console.log('in save')
if (err)
res.send(err);
res.json({ message: 'Bear created!' });
});
});
app.use('/api', router);
app.listen(port);
console.log('connected to port ' + port);
and
./app/models/bear.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var BearSchema = new Schema({
name: String
});
module.exports = mongoose.model('Bear', BearSchema);
My problem is, when I try the following request :
It doesn't return anything. I tried to console.log something in bear.save but in never goes in.
I don't get what I am doing wrong. Also when I try to connect to my mongolab db from my terminal it works perfectly well.
There's a problem with your index.js. Here, use this code:
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/test');
var Bear = require('./bear');
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(bodyParser.json());
var port = process.env.PORT || 8080;
var router = express.Router();
router.use(function (req, res, next) {
console.log('request called');
next();
});
router.get('/', function (req, res) {
res.json({
message: 'in /'
});
});
/*router.route('/bears')*/
router.post('/bears', function (req, res) {
console.log("request: " + JSON.stringify(req.body));
var bear = new Bear();
bear.name = req.body.name;
console.log(bear.name);
bear.save(function (err) {
console.log('in save')
if (err)
res.send(err);
res.json({
message: 'Bear created!'
});
});
});
app.use('/api', router);
app.listen(port);
console.log('connected to port ' + port);

Resources