MongoDB insertOne() buffering timed out after 10000ms - javascript

I am trying to use 'POST' to create a new movie data with using MongoDB. but when I use 'postman' to post my data it kepts saying like this
{"message":"Operation movies.insertOne() buffering timed out after 10000ms"}
I will post three javascript files please let me know about my problem.
First : index
Second : movie(module)
Third : routes
const router = express.Router();
const Movie = require('./models/movie');
//Fetch all movies
router.get("/movies", async (req, res) => {
try {
const movies = await Movie.find();
res.send(movies)
} catch(err) {
return res.status(500).json({message: err.message});
}
})
// Add movie
router.post("/movies", async (req, res) => {
const movie = new Movie({
title: req.body.title,
director: req.body.director,
year: req.body.year
});
try {
const newMovie = await movie.save();
res.status(201).json({ newMovie });
} catch(err) {
return res.status(500).json({ message: err.message });
}
})
module.exports = router;
//from here is Movie.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var MovieSchema = new Schema(
{
title: {type: String, required: true, maxlength: 150},
director: {type: String, required: true, maxlength: 200},
year: {type: Number, required: true}
}
);
//Export model
module.exports = mongoose.model('Movie', MovieSchema);
// from here is routes.js
const express = require('express');
const router = express.Router();
const Movie = require('./models/movie');
//Fetch all movies
router.get("/movies", async (req, res) => {
try {
const movies = await Movie.find();
res.send(movies)
} catch(err) {
return res.status(500).json({message: err.message});
}
})
// Add movie
router.post("/movies", async (req, res) => {
const movie = new Movie({
title: req.body.title,
director: req.body.director,
year: req.body.year
});
try {
const newMovie = await movie.save();
res.status(201).json({ newMovie });
} catch(err) {
return res.status(500).json({ message: err.message });
}
})
enter code here
module.exports = router;
I feel this is so hard to understand lol

Try to refactor your code like this:
router.post("/movies", async (req, res) => {
try {
let newMovie = await Movie.create(req.body);
res.status(201).json(newMovie);
} catch(err) {
return res.status(500).json({ message: err.message });
}
})

In the provided code I don't see you that you are connecting to the database using mongoose.connect for example:
mongoose.connect('mongodb://localhost/test', {useNewUrlParser: true, useUnifiedTopology: true});
Link for the docs.

Related

MVC - Adding Update Functionality to the Model - Node.js Express & MongoDB

I'm developing a Node.js Express & MongoDB web application.
Actually, I'm trying to use the MVC feature. However, there is a problem with my code after that I added the update functionality to the model.
Indeed, when I try to update a post, my application crashes and I get the following error message:
TypeError: C:\Users\DELL\Desktop\node-com4muz-database-mvc\views\admin\posts-list.ejs:19
17| <ol id="posts-list">
18| <% for (const post of posts) { %>
>> 19| <li><%- include('includes/post-item', { post: post }) %></li>
20| <% } %>
21| </ol>
22| <% } %>
C:\Users\DELL\Desktop\node-com4muz-database-mvc\views\admin\includes\post-item.ejs:3
1| <article class="post-item">
2| <h2><%= post.title %></h2>
>> 3| <p class="post-item-author">Rédigé par <%= post.author.name %></p>
4| <p><%= post.summary %></p>
5| <div class="post-actions">
6| <form action="/blog/<%= post._id %>/delete" method="POST">
Cannot read properties of undefined (reading 'name')
at eval ("C:\\Users\\DELL\\Desktop\\node-com4muz-database-mvc\\views\\admin\\includes\\post-item.ejs":15:38)
at post-item (C:\Users\DELL\Desktop\node-com4muz-database-mvc\node_modules\ejs\lib\ejs.js:703:17)
at include (C:\Users\DELL\Desktop\node-com4muz-database-mvc\node_modules\ejs\lib\ejs.js:701:39)
at eval ("C:\\Users\\DELL\\Desktop\\node-com4muz-database-mvc\\views\\admin\\posts-list.ejs":29:17)
at posts-list (C:\Users\DELL\Desktop\node-com4muz-database-mvc\node_modules\ejs\lib\ejs.js:703:17)
at tryHandleCache (C:\Users\DELL\Desktop\node-com4muz-database-mvc\node_modules\ejs\lib\ejs.js:274:36)
at View.exports.renderFile [as engine] (C:\Users\DELL\Desktop\node-com4muz-database-mvc\node_modules\ejs\lib\ejs.js:491:10)
at View.render (C:\Users\DELL\Desktop\node-com4muz-database-mvc\node_modules\express\lib\view.js:135:8)
at tryRender (C:\Users\DELL\Desktop\node-com4muz-database-mvc\node_modules\express\lib\application.js:657:10)
at Function.render (C:\Users\DELL\Desktop\node-com4muz-database-mvc\node_modules\express\lib\application.js:609:3) {
path: 'C:\\Users\\DELL\\Desktop\\node-com4muz-database-mvc\\views\\admin\\posts-list.ejs'
}
Actually, before I changed the code in the model file (see below) and the route file (see below), the update functionality was working fine.
That's the reason why I think we should compare both codes, before and after adding the update functionality to the model, to find where is the issue.
Here is my code before adding the update functionality to the model:
routes\admin\blog.js:
const express = require('express');
const mongodb = require('mongodb');
const multer = require('multer');
const storageConfig = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, 'public/admin/images');
},
filename: function (req, file, cb) {
cb(null, Date.now() + '-' + file.originalname);
}
});
const db = require('../../data/database');
const Post = require('../../models/post');
const ObjectId = mongodb.ObjectId;
const upload = multer({ storage: storageConfig });
const router = express.Router();
router.get('/posts', async function (req, res) {
const posts = await db
.getDb()
.collection('posts')
.find({})
.project({ title: 1, summary: 1, 'author.name': 1 })
.toArray();
res.render('posts-list', { posts: posts });
});
router.get('/new-post', async function (req, res) {
const authors = await db.getDb().collection('authors').find().toArray();
res.render('create-post', { authors: authors });
});
router.post('/new-post', upload.single('image'), async function (req, res) {
const uploadedImageFile = req.file;
const authorId = new ObjectId(req.body.author);
const author = await db
.getDb()
.collection('authors')
.findOne({ _id: authorId });
const enteredTitle = req.body.title;
const enteredSummary = req.body.summary;
const enteredContent = req.body.content;
const date = new Date();
const selectedAuthor = {
author: {
id: authorId,
name: author.name,
email: author.email
}
};
const selectedImage = uploadedImageFile.path;
const post = new Post(
enteredTitle,
enteredSummary,
enteredContent,
date,
selectedAuthor.author,
selectedImage
);
await post.save();
res.redirect('/posts');
});
router.get('/blog/:id/edit', async function (req, res) {
const postId = req.params.id;
const post = await db
.getDb()
.collection('posts')
.findOne(
{ _id: new ObjectId(postId) },
{ title: 1, summary: 1, content: 1 }
);
if (!post) {
return res.status(404).render('404');
}
res.render('update-post', { post: post });
});
router.post('/blog/:id/edit', async function (req, res) {
const postId = new ObjectId(req.params.id);
const result = await db
.getDb()
.collection('posts')
.updateOne(
{ _id: postId },
{
$set: {
title: req.body.title,
summary: req.body.summary,
content: req.body.content
// date: new Date()
}
}
);
res.redirect('/posts');
});
router.post('/blog/:id/delete', async function (req, res) {
const postId = new ObjectId(req.params.id);
const result = await db
.getDb()
.collection('posts')
.deleteOne({ _id: postId });
res.redirect('/posts');
});
router.get('/admin', async function (req, res) {
if (!res.locals.isAuth) {
// if (!req.session.user)
return res.status(401).render('401');
}
if (!res.locals.isAdmin) {
return res.status(403).render('403');
}
res.render('admin');
});
module.exports = router;
models\post.js:
const db = require('../data/database');
class Post {
constructor(title, summary, content, date, author, image, id) {
this.title = title;
this.summary = summary;
this.content = content;
this.date = date;
this.author = author;
this.image = image;
this.id = id; // may be undefined
}
async save() {
const newPost = {
title: this.title,
summary: this.summary,
content: this.content,
date: this.date,
author: this.author,
imagePath: this.image
};
const result = await db.getDb().collection('posts').insertOne(newPost);
// console.log(result);
return result;
}
}
module.exports = Post;
And here is the code after adding the update functionality to the model:
routes\admin\blog.js:
const express = require('express');
const mongodb = require('mongodb');
const multer = require('multer');
const storageConfig = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, 'public/admin/images');
},
filename: function (req, file, cb) {
cb(null, Date.now() + '-' + file.originalname);
}
});
const db = require('../../data/database');
const Post = require('../../models/post');
const ObjectId = mongodb.ObjectId;
const upload = multer({ storage: storageConfig });
const router = express.Router();
router.get('/posts', async function (req, res) {
const posts = await db
.getDb()
.collection('posts')
.find({})
.project({ title: 1, summary: 1, content: 1, 'author.name': 1 })
.toArray();
res.render('posts-list', { posts: posts });
});
router.get('/new-post', async function (req, res) {
const authors = await db.getDb().collection('authors').find().toArray();
res.render('create-post', { authors: authors });
});
router.post('/new-post', upload.single('image'), async function (req, res) {
const uploadedImageFile = req.file;
const authorId = new ObjectId(req.body.author);
const author = await db
.getDb()
.collection('authors')
.findOne({ _id: authorId });
const enteredTitle = req.body.title;
const enteredSummary = req.body.summary;
const enteredContent = req.body.content;
const date = new Date();
const selectedAuthor = {
author: {
id: authorId,
name: author.name,
email: author.email
}
};
const selectedImage = uploadedImageFile.path;
const post = new Post(
enteredTitle,
enteredSummary,
enteredContent,
date,
selectedAuthor.author,
selectedImage
);
await post.save();
res.redirect('/posts');
});
router.get('/blog/:id/edit', async function (req, res) {
const postId = req.params.id;
const post = await db
.getDb()
.collection('posts')
.findOne(
{ _id: new ObjectId(postId) },
{ title: 1, summary: 1, content: 1 }
);
if (!post) {
return res.status(404).render('404');
}
res.render('update-post', { post: post });
});
router.post('/blog/:id/edit', async function (req, res) {
const enteredTitle = req.body.title;
const enteredSummary = req.body.summary;
const enteredContent = req.body.content;
const post = new Post(
enteredTitle,
enteredSummary,
enteredContent,
req.params.id
);
await post.save();
res.redirect('/posts');
});
router.post('/blog/:id/delete', async function (req, res) {
const postId = new ObjectId(req.params.id);
const result = await db
.getDb()
.collection('posts')
.deleteOne({ _id: postId });
res.redirect('/posts');
});
router.get('/admin', async function (req, res) {
if (!res.locals.isAuth) {
// if (!req.session.user)
return res.status(401).render('401');
}
if (!res.locals.isAdmin) {
return res.status(403).render('403');
}
res.render('admin');
});
module.exports = router;
models\post.js:
const mongodb = require('mongodb');
const db = require('../data/database');
const ObjectId = mongodb.ObjectId;
class Post {
constructor(title, summary, content, date, author, image, id) {
this.title = title;
this.summary = summary;
this.content = content;
this.date = date;
this.author = author;
this.image = image;
if (id) {
this.id = new ObjectId(id);
}
}
async save() {
let result;
if (this.id) {
result = await db
.getDb()
.collection('posts')
.updateOne(
{ _id: postId },
{
$set: {
title: this.id,
summary: this.summary,
content: this.content
}
}
);
} else {
result = await db.getDb().collection('posts').insertOne({
title: this.title,
summary: this.summary,
content: this.content,
date: this.date,
author: this.author,
imagePath: this.image
});
}
return result;
}
}
module.exports = Post;
You're passing id as a wrong argument to when creating post object under /blog/:id/edit route, it doesn't get picked up, so it saves the post, instead of updating it, making other properties undefined.
Try this, pass 3 undefined arguments before id, which is passed as the last argument under /blog/:id/edit route:
const post = new Post(
enteredTitle,
enteredSummary,
enteredContent,
...[,,,], // pass 3 undefined arguments
req.params.id
);
await post.save();

There is some issue when I try to get data from mongodb by node.js?

This is my index.js. When I hit my API using postman, there is a bug in my getdata() method code that causes it to return the else statement rather than finding the requested resource. I'm not sure why the data targeting by ID can't be found. When I use console.log to test my code, the try statement is entered but did not find anything from the database and catch statement is returned.
const connectToMongo = require('./db');
var cors = require('cors');
const express = require('express');
const bodyParser = require('body-parser');
const photo = require('./models/photoModel');
const formidable = require('formidable');
const fs = require('fs');
const photoModel = require('./models/photoModel');
connectToMongo();
const app = express();
app.use(cors());
const port = 5000;
//app.use(express.json());
app.use(bodyParser.json());
const userData = (req, res) => {
const form = new formidable.IncomingForm();
console.log('1');
form.parse(req, (err, fields, file) => {
console.log('2');
if (fields) {
console.log('3');
const { email, mno, name } = fields;
if (!email || !mno || !name) {
console.log('4');
return res.status(400).json({
error: 'Fill all the fields',
});
}
}
if (file.photo) {
if (file.photo.size > 4000000) {
return res.status(400).json({
error: 'image size is too long',
});
}
const user = new photo(fields);
user.photo.data = fs.readFileSync(file.photo.filepath);
user.photo.contentType = file.photo.type;
user.save((err, user) => {
if (err) {
return res.status(400).json({
error: 'Not save in db',
});
}
console.log('above json');
res.json(user);
});
}
});
};
// The issue is here
const getdata = async (req, res) => {
try {
console.log('yes');
const photo = await photo.find({ photo: req.photo.id });
res.json(photo);
} catch (error) {
return res.status(400).json({
error: 'not find',
});
}
};
//router
app.post('/userdashboard', userData);
app.get('/getdata', getdata);
app.listen(port, () => {
console.log(`Dashboard Backend listening on port ${port}`);
});
This is my modelschema
const mongoose = require('mongoose');
const { Schema } = mongoose;
const PhotoSchema = new Schema({
name:{
type:String,
trim:true,
required:true
},
email:{
type:String,
trim:true,
required:true
},
photo:{
data:Buffer,
contentType:String
},
mno:{
type:Number,
required:true
}
});
module.exports=mongoose.model('photo',PhotoSchema);
First mistake you did was not adding console.error(error), if you did it would have shown exact error message.
In this case req.photo is undefined and you are trying to access id property of undefined which causes error to be thrown.
const getdata = async (req, res) => {
try {
const { photo } = req.body
// TODO: use custom error class for validation errors instead of default Error class
if (!photo) throw new Error('photo is missing')
if (!photo.id) throw new Error('photo.id is missing')
// TODO: validate photo.id is valid monogoid
const photos = await photo.find({ photo: photo.id })
res.json(photos)
} catch (error) {
console.error(error) // <-- this was missing
res.status(400).json({ error: 'not find' }) // provide good error message
return
}
}

MongoDB with node.js trying to make a new file (JavaScript)

I wrote a little of code to start learning MongoDB with Node.js in JavaScript but it doesn't work but it doesn't
give a error while running probably someone can help me with that.
The Main code:
const mongoose = require('mongoose');
const express = require('express');
const test = express();
const Blog = require('./bdSchema');
//connec to mongodb
const dbURI = 'mongodb+srv://Carsten:<int the real code the password is here>#cluster0.w6iwv.mongodb.net/tomhatesgeschaft?retryWrites=true&w=majority';
mongoose.connect(dbURI, { useNewUrlParser: true, useUnifiedTopology: true })
.then((result) => console.log("connected to db"))
.catch((err) => console.log(err))
test.get('/add-tomhatesgeschaft', (req, res) => {
const tomhatesgeschaft = new Blog({
title: 'hi'
});
tomhatesgeschaft.save()
.then((result) => {
res.send(result)
})
.catch((err) => {
console.log(err);
});
})
The BDSchema:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const BDSchema = new Schema({
title: {
type: String,
required: true,
},
});
const Blog = mongoose.model('Blog', BDSchema);
module.exports = Blog;
In your Node.js code, change the save function as below.
tomhatesgeschaft.save((err,result) => {
if (err){
console.error(err);
}
else{
res.send(result)
})
})
OR
test.get('/add-tomhatesgeschaft', async (req, res) => {
const tomhatesgeschaft = new Blog({
title: 'hi'
});
try {
await tomhatesgeschaft.save()
} catch(error) {
console.error(error)
}
})
PS: You should not use GET requests for operations such as saving data to the database. Ideally, you should use a POST request.
Example with async:
test.post('/add-tomhatesgeschaft', async (req, res) => {
const tomhatesgeschaft = new Blog({
title: 'hi'
});
try {
await tomhatesgeschaft.save()
} catch(error) {
console.error(error)
}
})

expressJs router.post() not working for multiple middleware giving [object Undefined] error

i am creating a REST API for my users, and i used express-validator for the validation before creating the user in the database.. but when i chain my middleware together in the router.py file it gives the error Error: Route.post() requires a callback function but got a [object Undefined]
i imported my middleware and controller from thier respective files.
here is the code in my router.py
const express = require('express');
const authMiddleware = require('../middlewares/authMiddleware');
const authController = require('../controllers/authController');
const router = express.Router();
router.post(
'/signup',
authMiddleware.verifySignUpInit(),
authMiddleware.verifySignUp,
authController.signup
);
module.exports = router;
in my middleware file i added this..
const jwt = require('jsonwebtoken');
const { authentication } = require('../config');
const { User } = require('../models');
const { body } = require('express-validator');
const verifySignUpInit = () => {
return [
body('email', 'email is required').exists().normalizeEmail().isEmail(),
body('phone', 'phone is required').exists().isInt(),
body('first_name', 'first_name is required').exists().isString(),
body('last_name', 'last_name is required').exists().isString(),
body('password', 'password is required').exists(),
];
};
const verifySignUp = (req, res, next) => {
const { email, phone, password } = req.body;
User.findOne({
email,
}).exec((err, user) => {
if (err) {
res.status(500).json({
status: 'error',
message: err,
});
}
if (user) {
return res.status(400).json({
status: 'failed',
message: 'Email Provided Already Exists',
});
}
});
User.findOne({
phone,
}).exec((err, user) => {
if (err) {
res.status(500).json({
status: 'error',
message: err,
});
}
if (user) {
return res.status(400).json({
status: 'failed',
message: 'Phone Provided Already Exists',
});
}
});
const password_is_valid = authentication.passwordSchema.validate(password);
if (!password_is_valid) {
return res.status(400).json({
status: 'failed',
message: 'password requirements not met',
});
}
next();
};
module.exports = {
verifySignUpInit,
verifySignUp,
};
and finally in my controller i have this..
const config = require('../config');
const db = require('../models');
var jwt = require('jsonwebtoken');
var bcrypt = require('bcryptjs');
const { validationResult } = require('express-validator');
const { User, Role } = db;
const { token_expiry_time, refresh_token_expiry_time } = config.authentication;
const signUp = (req, res) => {
const { email, phone, first_name, last_name, password } = req.body;
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({
status: 'failed',
message: errors.array(),
});
}
bcrypt.hash(password, 8, (err, hash) => {
if (err) {
return res.status(500).json({
status: 'error',
message: err,
});
}
const user = new User({
first_name: first_name,
last_name: last_name,
email: email,
phone: phone,
password: hash,
});
Role.findOne({ name: 'is_user' }, (err, role) => {
if (err) {
res.status(500).json({
status: 'error',
message: err,
});
return;
}
user.roles = [role._id];
user.save((err) => {
if (err) {
return res.status(500).json({
status: 'error',
message: err,
});
}
return res.status(201).json({
status: 'success',
data: {
user,
},
});
});
});
});
};
module.exports = {
signUp,
};
i cant tell what i am doing wrong :(
authController.signup
should be:
authController.signUp
You have to use the same capitalization for the property name you exported.

NodeJS MonogoDB Postman Post Request throwing an Error probably the objectID Error

hi there I am learning node js quite a while but facing an error which becomes to really hard to fix it for my own self after spending to much time I got the cause of which is I may be passing ObjectID in a wrong manner although my endpoint is working ok I can't call post-call in POSTMAN. here are some snippets
POSTMAN Post request by Json
{
"genreId":"5f65c490db297fa17cd4f060",
"title": "Trminator",
"numberInStock": 0,
"dailyRentalRate": 0
}
ERROR in terminal
UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'genreId' of undefined
at C:\Users\Sharjeel MK\Desktop\Project- Build the Genres API\routes\movies.js:16:47
index.js
const express = require ('express');
const app=express();
const home=require('./routes/home');
const genres=require('./routes/genres');
const customers=require('./routes/customers');
const movies = require('./routes/movies')
const mongoose=require('mongoose');
mongoose.connect('mongodb://localhost/vidly',{
keepAlive: true,
useNewUrlParser: true,
useCreateIndex: true,
useFindAndModify: false,
useUnifiedTopology: true
})
.then(()=>console.log("connected")).
catch((e)=>console.log('not connnected',e));
app.use('/',home);
app.use('/vidly.com/api/genres',genres);
app.use('/vidly.com/api/customers',customers);
app.use('/vidly.com/api/movies',movies);
const port=process.env.PORT||3000;
app.listen(port,()=>{
console.log(`${port} listening`);})
in routes movie.js
const {Movie, validate} = require('../model/movieModel');
const {Genre} = require('../model/genreModel');
const mongoose = require('mongoose');
const express = require('express');
const routes = express.Router();
routes.get('/', async (req, res) => {
const movies = await Movie.find().sort('name');
res.send(movies);
});
routes.post('/', async (req, res) => {
const { error } = validate(req.body);
if (error) return res.status(400).send(error.details[0].message);
const genre = await Genre.findById(req.body.genreId);
if (!genre) return res.status(400).send('Invalid genre.');
let movie = new Movie({
title: req.body.title,
genre: {
_id: genre._id,
name: genre.name
},
numberInStock: req.body.numberInStock,
dailyRentalRate: req.body.dailyRentalRate
});
movie = await movie.save();
res.send(movie);
});
routes.put('/:id', async (req, res) => {
const { error } = validate(req.body);
if (error) return res.status(400).send(error.details[0].message);
const genre = await Genre.findById(req.body.genreId);
if (!genre) return res.status(400).send('Invalid genre.');
const movie = await Movie.findByIdAndUpdate(req.params.id,
{
title: req.body.title,
genre: {
_id: genre._id,
name: genre.name
},
numberInStock: req.body.numberInStock,
dailyRentalRate: req.body.dailyRentalRate
}, { new: true });
if (!movie) return res.status(404).send('The movie with the given ID was not found.');
res.send(movie);
});
routes.delete('/:id', async (req, res) => {
const movie = await Movie.findByIdAndRemove(req.params.id);
if (!movie) return res.status(404).send('The movie with the given ID was not found.');
res.send(movie);
});
routes.get('/:id', async (req, res) => {
const movie = await Movie.findById(req.params.id);
if (!movie) return res.status(404).send('The movie with the given ID was not found.');
res.send(movie);
});
module.exports = routes;
schema model of movies
const Joi = require('joi');
const mongoose = require('mongoose');
const {genreSchema} = require('./genreModel');
const Movie = mongoose.model('Movies', new mongoose.Schema({
title: {
type: String,
required: true,
trim: true,
minlength: 5,
maxlength: 255
},
genre: {
type: genreSchema,
required: true
},
numberInStock: {
type: Number,
required: true,
min: 0,
max: 255
},
dailyRentalRate: {
type: Number,
required: true,
min: 0,
max: 255
}
}));
function validateMovie(movie) {
const schema = {
title: Joi.string().min(5).max(50).required(),
genreId: Joi.string().required(),
numberInStock: Joi.number().min(0).required(),
dailyRentalRate: Joi.number().min(0).required()
};
return Joi.validate(movie, schema);
}
exports.Movie = Movie;
exports.validate = validateMovie;
User findOne -> here is the syntax
var query = {
genreId : req.body.genreId
}
Model-Name.findOne(query, function(err, result){
if(err) throw err
else res.send(200, result)
})
so after spending 2 days finally figure out the error the reason was so much simpler I didn't pass express.json() in my index.js file for incoming Request Object as a JSON Object. that's why it was throwing the error cause not handle properly.
Previous code
const express = require ('express');
const app=express();
const home=require('./routes/home');
const genres=require('./routes/genres');
const customers=require('./routes/customers');
const movies = require('./routes/movies')
const mongoose=require('mongoose');
mongoose.connect('mongodb://localhost/vidly',{
keepAlive: true,
useNewUrlParser: true,
useCreateIndex: true,
useFindAndModify: false,
useUnifiedTopology: true
})
.then(()=>console.log("connected")).
catch((e)=>console.log('not connnected',e));
app.use('/',home);
app.use('/vidly.com/api/genres',genres);
app.use('/vidly.com/api/customers',customers);
app.use('/vidly.com/api/movies',movies);
const port=process.env.PORT||3000;
app.listen(port,()=>{
console.log(`${port} listening`);})
updated code
const express = require ('express');
const app=express();
const home=require('./routes/home');
const genres=require('./routes/genres');
const customers=require('./routes/customers');
const movies = require('./routes/movies')
const mongoose=require('mongoose');
mongoose.connect('mongodb://localhost/vidly',{
keepAlive: true,
useNewUrlParser: true,
useCreateIndex: true,
useFindAndModify: false,
useUnifiedTopology: true
})
.then(()=>console.log("connected")).
catch((e)=>console.log('not connnected',e));
app.use(express.json());
app.use('/',home);
app.use('/vidly.com/api/genres',genres);
app.use('/vidly.com/api/customers',customers);
app.use('/vidly.com/api/movies',movies);
const port=process.env.PORT||3000;
app.listen(port,()=>{
console.log(`${port} listening`);
})

Categories

Resources