Express is one of the most popular web frameworks for Node.js that supports routing, middleware, view system… Mongoose is a promise-based Node.js ODM for MongoDB that provides a straight-forward, schema-based solution to model our application data along with built-in type casting, validation, query building, business logic hooks… In this tutorial, I will show you step by step to build Node.js Restful API for CRUD operations using Express, Mongoose with MongoDB database.
You should install MongoDB in your machine first. The installation instructions can be found at Official MongoDB installation manual.
Fullstack:
– MEVN: Vue.js + Node.js + Express + MongoDB example
– MEAN:
Angular 8 + Node.js + Express + MongoDB example
Angular 10 + Node.js + Express + MongoDB example
Angular 11 + Node.js + Express + MongoDB example
Angular 12 + Node.js + Express + MongoDB example
Angular 13 + Node.js + Express + MongoDB example
Angular 14 + Node.js + Express + MongoDB example
– MERN: React + Node.js + Express + MongoDB example
Security: Node.js + MongoDB: User Authentication & Authorization with JWT
Deployment: Docker Compose: Node.js Express and MongoDB example
Contents
Node.js MongoDB Rest CRUD API overview
We will build Rest Apis that can create, retrieve, update, delete and find Tutorials by title.
First, we start with an Express web server. Next, we add configuration for MongoDB database, create Tutorial
model with Mongoose, write the controller. Then we define routes for handling all CRUD operations (including custom finder).
The following table shows overview of the Rest APIs that will be exported:
Methods | Urls | Actions |
---|---|---|
GET | api/tutorials | get all Tutorials |
GET | api/tutorials/:id | get Tutorial by id |
POST | api/tutorials | add new Tutorial |
PUT | api/tutorials/:id | update Tutorial by id |
DELETE | api/tutorials/:id | remove Tutorial by id |
DELETE | api/tutorials | remove all Tutorials |
GET | api/tutorials/published | find all published Tutorials |
GET | api/tutorials?title=[kw] | find all Tutorials which title contains 'kw' |
Finally, we’re gonna test the Rest Apis using Postman.
This is our project structure:
Demo Video
This is our Node.js Express MongoDB application brief instruction and demo, test Rest Apis with Postman.
Create Node.js App
First, we create a folder:
$ mkdir nodejs-express-mongodb
$ cd nodejs-express-mongodb
Next, we initialize the Node.js App with a package.json file:
npm init
name: (nodejs-express-mongodb)
version: (1.0.0)
description: Node.js Restful CRUD API with Node.js, Express and MongoDB
entry point: (index.js) server.js
test command:
git repository:
keywords: nodejs, express, mongodb, rest, api
author: bezkoder
license: (ISC)
Is this ok? (yes) yes
We need to install necessary modules: express
, mongoose
and cors
.
Run the command:
npm install express mongoose cors --save
The package.json file should look like this:
{
"name": "node-express-mongodb",
"version": "1.0.0",
"description": "Node.js Restful CRUD API with Node.js, Express and MongoDB",
"main": "server.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [
"nodejs",
"express",
"rest",
"api",
"mongodb"
],
"author": "bezkoder",
"license": "ISC",
"dependencies": {
"cors": "^2.8.5",
"express": "^4.18.1",
"mongoose": "^6.4.2"
}
}
Setup Express web server
In the root folder, let’s create a new server.js file:
const express = require("express");
const cors = require("cors");
const app = express();
var corsOptions = {
origin: "http://localhost:8081"
};
app.use(cors(corsOptions));
// parse requests of content-type - application/json
app.use(express.json());
// parse requests of content-type - application/x-www-form-urlencoded
app.use(express.urlencoded({ extended: true }));
// simple route
app.get("/", (req, res) => {
res.json({ message: "Welcome to bezkoder application." });
});
// set port, listen for requests
const PORT = process.env.PORT || 8080;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}.`);
});
What we do are:
– import express
and cors
modules:
- Express is for building the Rest apis
- cors provides Express middleware to enable CORS with various options.
– create an Express app, then add body-parser (json
and urlencoded
) and cors
middlewares using app.use()
method. Notice that we set origin: http://localhost:8081
.
– define a GET route which is simple for test.
– listen on port 8080 for incoming requests.
Now let’s run the app with command: node server.js
.
Open your browser with url http://localhost:8080/, you will see:
Yeah, the first step is done. We’re gonna work with Mongoose in the next section.
Configure MongoDB database & Mongoose
In the app folder, we create a separate config folder for configuration with db.config.js file like this:
module.exports = {
url: "mongodb://localhost:27017/bezkoder_db"
};
Define Mongoose
We’re gonna define Mongoose model (tutorial.model.js) also in app/models folder in the next step.
Now create app/models/index.js with the following code:
const dbConfig = require("../config/db.config.js");
const mongoose = require("mongoose");
mongoose.Promise = global.Promise;
const db = {};
db.mongoose = mongoose;
db.url = dbConfig.url;
db.tutorials = require("./tutorial.model.js")(mongoose);
module.exports = db;
Don’t forget to call connect()
method in server.js:
...
const app = express();
app.use(...);
const db = require("./app/models");
db.mongoose
.connect(db.url, {
useNewUrlParser: true,
useUnifiedTopology: true
})
.then(() => {
console.log("Connected to the database!");
})
.catch(err => {
console.log("Cannot connect to the database!", err);
process.exit();
});
Define the Mongoose Model
In models folder, create tutorial.model.js file like this:
module.exports = mongoose => {
const Tutorial = mongoose.model(
"tutorial",
mongoose.Schema(
{
title: String,
description: String,
published: Boolean
},
{ timestamps: true }
)
);
return Tutorial;
};
This Mongoose Model represents tutorials collection in MongoDB database. These fields will be generated automatically for each Tutorial document: _id, title, description, published, createdAt, updatedAt, __v.
{
"_id": "5e363b135036a835ac1a7da8",
"title": "Js Tut#",
"description": "Description for Tut#",
"published": true,
"createdAt": "2020-02-02T02:59:31.198Z",
"updatedAt": "2020-02-02T02:59:31.198Z",
"__v": 0
}
If you use this app with a front-end that needs id field instead of _id, you have to override toJSON
method that map default object to a custom object. So the Mongoose model could be modified as following code:
module.exports = mongoose => {
var schema = mongoose.Schema(
{
title: String,
description: String,
published: Boolean
},
{ timestamps: true }
);
schema.method("toJSON", function() {
const { __v, _id, ...object } = this.toObject();
object.id = _id;
return object;
});
const Tutorial = mongoose.model("tutorial", schema);
return Tutorial;
};
And the result will look like this-
{
"title": "Js Tut#",
"description": "Description for Tut#",
"published": true,
"createdAt": "2020-02-02T02:59:31.198Z",
"updatedAt": "2020-02-02T02:59:31.198Z",
"id": "5e363b135036a835ac1a7da8"
}
After finishing the steps above, we don’t need to write CRUD functions, Mongoose Model supports all of them:
- create a new Tutorial: object.save()
- find a Tutorial by id: findById(id)
- retrieve all Tutorials: find()
- update a Tutorial by id: findByIdAndUpdate(id, data)
- remove a Tutorial: findByIdAndRemove(id)
- remove all Tutorials: deleteMany()
- find all Tutorials by title: find({ title: { $regex: new RegExp(title), $options: “i” } })
These functions will be used in our Controller.
Create the Controller
Inside app/controllers folder, let’s create tutorial.controller.js with these CRUD functions:
- create
- findAll
- findOne
- update
- delete
- deleteAll
- findAllPublished
const db = require("../models");
const Tutorial = db.tutorials;
// Create and Save a new Tutorial
exports.create = (req, res) => {
};
// Retrieve all Tutorials from the database.
exports.findAll = (req, res) => {
};
// Find a single Tutorial with an id
exports.findOne = (req, res) => {
};
// Update a Tutorial by the id in the request
exports.update = (req, res) => {
};
// Delete a Tutorial with the specified id in the request
exports.delete = (req, res) => {
};
// Delete all Tutorials from the database.
exports.deleteAll = (req, res) => {
};
// Find all published Tutorials
exports.findAllPublished = (req, res) => {
};
Let’s implement these functions.
Create a new object
Create and Save a new Tutorial:
exports.create = (req, res) => {
// Validate request
if (!req.body.title) {
res.status(400).send({ message: "Content can not be empty!" });
return;
}
// Create a Tutorial
const tutorial = new Tutorial({
title: req.body.title,
description: req.body.description,
published: req.body.published ? req.body.published : false
});
// Save Tutorial in the database
tutorial
.save(tutorial)
.then(data => {
res.send(data);
})
.catch(err => {
res.status(500).send({
message:
err.message || "Some error occurred while creating the Tutorial."
});
});
};
Retrieve objects (with condition)
Retrieve all Tutorials/ find by title from the database:
exports.findAll = (req, res) => {
const title = req.query.title;
var condition = title ? { title: { $regex: new RegExp(title), $options: "i" } } : {};
Tutorial.find(condition)
.then(data => {
res.send(data);
})
.catch(err => {
res.status(500).send({
message:
err.message || "Some error occurred while retrieving tutorials."
});
});
};
We use req.query.title
to get query string from the Request and consider it as condition for findAll()
method.
Retrieve a single object
Find a single Tutorial with an id
:
exports.findOne = (req, res) => {
const id = req.params.id;
Tutorial.findById(id)
.then(data => {
if (!data)
res.status(404).send({ message: "Not found Tutorial with id " + id });
else res.send(data);
})
.catch(err => {
res
.status(500)
.send({ message: "Error retrieving Tutorial with id=" + id });
});
};
Update an object
Update a Tutorial identified by the id
in the request:
exports.update = (req, res) => {
if (!req.body) {
return res.status(400).send({
message: "Data to update can not be empty!"
});
}
const id = req.params.id;
Tutorial.findByIdAndUpdate(id, req.body, { useFindAndModify: false })
.then(data => {
if (!data) {
res.status(404).send({
message: `Cannot update Tutorial with id=${id}. Maybe Tutorial was not found!`
});
} else res.send({ message: "Tutorial was updated successfully." });
})
.catch(err => {
res.status(500).send({
message: "Error updating Tutorial with id=" + id
});
});
};
Delete an object
Delete a Tutorial with the specified id
:
exports.delete = (req, res) => {
const id = req.params.id;
Tutorial.findByIdAndRemove(id)
.then(data => {
if (!data) {
res.status(404).send({
message: `Cannot delete Tutorial with id=${id}. Maybe Tutorial was not found!`
});
} else {
res.send({
message: "Tutorial was deleted successfully!"
});
}
})
.catch(err => {
res.status(500).send({
message: "Could not delete Tutorial with id=" + id
});
});
};
Delete all objects
Delete all Tutorials from the database:
exports.deleteAll = (req, res) => {
Tutorial.deleteMany({})
.then(data => {
res.send({
message: `${data.deletedCount} Tutorials were deleted successfully!`
});
})
.catch(err => {
res.status(500).send({
message:
err.message || "Some error occurred while removing all tutorials."
});
});
};
Find all objects by condition
Find all Tutorials with published = true
:
exports.findAllPublished = (req, res) => {
Tutorial.find({ published: true })
.then(data => {
res.send(data);
})
.catch(err => {
res.status(500).send({
message:
err.message || "Some error occurred while retrieving tutorials."
});
});
};
This controller can be modified a little to return pagination response:
{
"totalItems": 8,
"tutorials": [...],
"totalPages": 3,
"currentPage": 1
}
You can find more details at:
Server side Pagination in Node.j with MongoDB & Mongoose
Define Routes
When a client sends request for an endpoint using HTTP request (GET, POST, PUT, DELETE), we need to determine how the server will reponse by setting up the routes.
These are our routes:
/api/tutorials
: GET, POST, DELETE/api/tutorials/:id
: GET, PUT, DELETE/api/tutorials/published
: GET
Create a tutorial.routes.js inside app/routes folder with content like this:
module.exports = app => {
const tutorials = require("../controllers/tutorial.controller.js");
var router = require("express").Router();
// Create a new Tutorial
router.post("/", tutorials.create);
// Retrieve all Tutorials
router.get("/", tutorials.findAll);
// Retrieve all published Tutorials
router.get("/published", tutorials.findAllPublished);
// Retrieve a single Tutorial with id
router.get("/:id", tutorials.findOne);
// Update a Tutorial with id
router.put("/:id", tutorials.update);
// Delete a Tutorial with id
router.delete("/:id", tutorials.delete);
// Delete all Tutorials
router.delete("/", tutorials.deleteAll);
app.use('/api/tutorials', router);
};
You can see that we use a controller from /controllers/tutorial.controller.js
.
We also need to include routes in server.js (right before app.listen()
):
...
require("./app/routes/tutorial.routes")(app);
// set port, listen for requests
const PORT = ...;
app.listen(...);
Test the APIs
Run our Node.js application with command: node server.js
.
Using Postman, we’re gonna test all the Apis above.
- Create a new Tutorial using
POST /tutorials
Api - Retrieve a single Tutorial by id using
GET /tutorials/:id
Api - Update a Tutorial using
PUT /tutorials/:id
Api - Find all Tutorials which title contains ‘js’:
GET /tutorials?title=js
- Find all published Tutorials using
GET /tutorials/published
Api - Delete a Tutorial using
DELETE /tutorials/:id
Api - Delete all Tutorials using
DELETE /tutorials
Api

After creating some new Tutorials, you can check MongoDb collection:
Check tutorials
collection after some documents were updated:
The Tutorial was removed from tutorials
collection:
You can use the Simple HTTP Client using Axios to check it.
Or: Simple HTTP Client using Fetch API
Conclusion
Today, we’ve learned how to create Node.js Rest Apis with an Express web server. We also know way to add configuration for MongoDB database & Mongoose, create a Mongoose Model, write a controller and define routes for handling all CRUD operations.
You can find more interesting thing in the next tutorial:
– Server side Pagination in Node.j with MongoDB & Mongoose
Return pagination data in response:
{
"totalItems": 8,
"tutorials": [...],
"totalPages": 3,
"currentPage": 1
}
How to build a fullstack system with this app as backend server in the posts:
– MEVN: Vue.js + Node.js + Express + MongoDB example
– MEAN:
Angular 8 + Node.js + Express + MongoDB example
Angular 10 + Node.js + Express + MongoDB example
Angular 11 + Node.js + Express + MongoDB example
Angular 12 + Node.js + Express + MongoDB example
Angular 13 + Node.js + Express + MongoDB example
Angular 14 + Node.js + Express + MongoDB example
– MERN: React + Node.js + Express + MongoDB example
Happy learning! See you again.
Further Reading
- Express.js Routing
- https://www.npmjs.com/package/express
- https://www.npmjs.com/package/mongoose
- https://mongoosejs.com/docs/guide.html
Deployment: Docker Compose: Node.js Express and MongoDB example
Source code
You can find the complete source code for this example on Github.
Great tutorials. I have not got a single issue. Thanks a lot.
you can check line by line code
Very interesting Node tutorial. Quite informative and very helpful. Thank you! Expect more tutorials in the future.
Hi,
Thanks a lot. Its very good article!
Thank you so much.
it was a great article!
Hi, when i try to test the post method on postMan, it only returns “localhost request not supported” to me.
Have you any guess about what maybe going wrong?
Hello, Thank you for the awesome tutorials.
I have found your small spelling mistake. You said, “Create a turorial.routes.js inside app/routes”. Not “turorial”, it should be “tutorial” :).
NICE TUTORIAL!
THANKS. IT WORKS.
This is good tutorial. It’ll be helpful for me.
I’ll follow your nice and proper instruction.
Thanks
Excellent tutorial. Thank you.
hi, I cloned your code from github and it gives this error, it’s the same error I was getting with my own code, what might be wrong?
internal/modules/cjs/loader.js:638
throw err;
^
Error: Cannot find module ‘express’
at Function.Module._resolveFilename (internal/modules/cjs/loader.js:636:15)
at Function.Module._load (internal/modules/cjs/loader.js:562:25)
at Module.require (internal/modules/cjs/loader.js:692:17)
at require (internal/modules/cjs/helpers.js:25:18)
at Object. (/mnt/c/Users/Siphe/OneDrive/Desktop/Momo/Stin/web/newF/Pew/JS/node-express-mongodb/server.js:1:17)
at Module._compile (internal/modules/cjs/loader.js:778:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)
at Module.load (internal/modules/cjs/loader.js:653:32)
at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
at Function.Module._load (internal/modules/cjs/loader.js:585:3)
You probably need to install your dependencies…try typing “npm i” in the command line.
Great tutorial; body-parser is now deprecated and express does the job : express.json() or express.urlencoded()
Thank you
Cannot connect to the database! MongooseServerSelectionError: connect ECONNREFUSED 127.0.0.1:27017,
Let me know what can be done
Hi, you need to run MongoDB first 🙂
so should I install Mongodb, do a database, and run it before starting this tutorial?? I’m confused
Yes, you must install MongoDB and run first.
For the people who is getting the message “Content can’t be empty”
Add this line into the server.js file
app.use(express.json());
Did you find out the answer?
Why is this happening.
Hello,
I tried to connect both of your tutorials (this one and JWT one) and when i try to add a tutorial I’ve got an error in the console:
TypeError: Tutorial is not a constructor
at exports.create (C:\Repo\pd_copy\app\controllers\tutorial.controller.js:13:20)
at Layer.handle [as handle_request] (C:\Repo\pd_copy\node_modules\express\lib\router\layer.js:95:5)
at next (C:\Repo\pd_copy\node_modules\express\lib\router\route.js:137:13)
at Route.dispatch (C:\Repo\pd_copy\node_modules\express\lib\router\route.js:112:3)
at Layer.handle [as handle_request] (C:\Repo\pd_copy\node_modules\express\lib\router\layer.js:95:5)
at C:\Repo\pd_copy\node_modules\express\lib\router\index.js:281:22
at Function.process_params (C:\Repo\pd_copy\node_modules\express\lib\router\index.js:335:12)
at next (C:\Repo\pd_copy\node_modules\express\lib\router\index.js:275:10)
at Function.handle (C:\Repo\pd_copy\node_modules\express\lib\router\index.js:174:3)
at router (C:\Repo\pd_copy\node_modules\express\lib\router\index.js:47:12)
at Layer.handle [as handle_request] (C:\Repo\pd_copy\node_modules\express\lib\router\layer.js:95:5)
at trim_prefix (C:\Repo\pd_copy\node_modules\express\lib\router\index.js:317:13)
at C:\Repo\pd_copy\node_modules\express\lib\router\index.js:284:7
at Function.process_params (C:\Repo\pd_copy\node_modules\express\lib\router\index.js:335:12)
at next (C:\Repo\pd_copy\node_modules\express\lib\router\index.js:275:10)
at C:\Repo\pd_copy\app\routes\user.routes.js:10:5
https://i.imgur.com/eaIRA2A.png – the error
https://pastebin.com/QKq8EJ6x – tutorial.controller.js
Could you help?
I was doing it wrong by doing const Tutorial = db.tutorials();
Here I was not supposed to use the parathesis.
Hi,
I’ve finished to implement ur tutorial. Thanks a lot! But I’m getting error when I try (with postam) to do POST / CREATE :
message”: “user is not allowed to do action [insert] on [Cluster0.tutorials]”
Could you help?
Set your permissions on MongoDB Atlas.
Hi, thanks for this tutorial.
I am getting this error:
require(“./app/routes/tutorial.routes”)(app);
^
TypeError: require(…) is not a function
at Object. (/Users/la96244/projects/rk-poc/nodejs-express-mongodb/server.js:41:40)
at Module._compile (internal/modules/cjs/loader.js:759:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:770:10)
at Module.load (internal/modules/cjs/loader.js:628:32)
at Function.Module._load (internal/modules/cjs/loader.js:555:12)
at Function.Module.runMain (internal/modules/cjs/loader.js:824:10)
at internal/main/run_main_module.js:17:11
Could you help?
Hi there! I enjoyed your tutorials very much! ?
Can I ask, why is it that you are able to get the list of tutorials by title using /api/tutorials?title=”abc” but you are not able to get list of tutorials by description using /api/tutorials?description=”abc”
Hi, you can get list of tutorials by description using
/api/tutorials?description=abc
by adding that API. It is similar to what you do with the title.How can I route this to admin dashboard when a successful login happens? Sorry im new to these stuff
Thank you so much for this tutorial. How do I avoid getting a CORS error when testing the API? Regardless of what browser I use, or whether or not I use CORS disabling plugins I get the following error “CORS Error: The request has been blocked because of the CORS policy”.
This blog really helped me a lot to learn. Thank You and please keep making such blogs.
I am having an issue, the whole back-end, and front-end is working fine but I am not able to edit, update, and publish the data. Because in the url section in the place of id (undefined) is showing. It seems like the id is not getting pass while clicking on the edit button.
please help me with the issue…
Hi, which frontend do you use?
Hi, Thanks a lot for this brilliant tutorial which go straight to the point. I have an error message when POSTing an new tutorial (TypeError: Cannot read property 'tutorial' of undefined). I can READ and DELETE but neither CREATE nor PUT though I have carefully checked your code and mine to be similar. Would you have an idea where this error could come from ?
Thanks !
Hi, you should set
'Content-Type': 'application/json'
in HTTP request header 🙂I want to combine this tutorial with node js mongodb authentication
the problem is how to read specific data based on the user account?
for example, I have 5 data and 2 users. the odd data belong to the first user and the even data belong to the second user
then if I logged in using the first user, I can only read the first, third, and fifth data
I think it’s possible to use one-to-many relations and using parent reference inside the data related to the username or objectID of the user
but I don’t understand how to make the controller to create data with the parent reference
any solutions on how this will be work?
Same here man…been stuck for a couple of days now
The line breaks have disappeared, so write it again.
Hi.
I am Japanese and use google translation.
Thanks for creating the MEVN stack description.
I want to create and run the following project locally.
↓ git clone
Created: August 25, 2020 (Modified: turorial⇒tutorial)
https://bezkoder.com/node-express-mongodb-crud-rest-api/
Created: 2020/8/3
https://bezkoder.com/vue-js-crud-app/
It works perfectly by itself, but it doesn’t exchange data between applications.
What is wrong?
Is it BaseURL?
I have no knowledge and I cannot solve the problem.
Can anyone give me some hints?
Hi, please show me the error log and browser console log 🙂
Hi,
Great step by step tutorial.
I have one requirement. How to retrieve one random document with a condition like where description has less than or equal to 10 words?
Regards,
Ash
Hi bezkoder,
I defined a new : “product.model.js” with 10 fields.
1) Isn’t it possible to define a new field as “integer” in the model ?
When restarting node :
ReferenceError: Integer is not defined
2) When
http://localhost:8080/api/products
only 2 fields are returned
How to achieve all fields will return ?
= Jannes
ad 2) is solved
The fields were not inserted, so empty = null.
= Jannes
thanks for this great tutorial. please do you have a tutorial for image file upload to mongodb or could you recommend one for me ?
Hi, fortunately I have this one:
How to upload/store images in MongoDB using Node.js, Express & Multer
Hi, nice work! Can I ask you if you can recommend me any good tutorial in order to learn how to create models and controllers alone?
Hi bezkoder,
Thanks a lot for such nice tutorial . Its working fine for me as expected. Please help me to understand the path URL where we are defining. http://localhost:8080/api/tutorials/5f1907207dbbe36230ec460d. For this url where is /api/tutorials/ in our code ?
Hi, you can see
app.use('/api/tutorials', router);
in app/routes/turorial.routes.js file. 🙂Thank you for the great tutorial.
I am getting and error. ‘Tutorial is not defined’
in my tutorial_controller when i try to post request to the API
Hello Adam, in the tutorial.controller.js change the statement
const tutorial = new Tutorial({
with
const tutorial = new db.tutorials({
Here we initialize an object of Tutorial model class and let’s solution the problem.
Thank you for the Tutorial. It is really well-written document, Will not to face a single problem if followed exactly. Great Job!
It works! Many thanks! You help me a lot! 😀
Hi Bezkoder,
Thank you for the tutorial! It is just amazing! I always hated javascript (I am mostly python dev) until I found your guide. Now everything much clearer to me.
Can I ask you to give an update for this awesome article so each tutorial has an image that can be uploaded during tutorial creation?
Thank you in advance!
Nice tutorial and very helpful.
Is it possible to display a message when there is no published tutorial? (tutorial.controller.js/exports.findAllPublished)
Hey,
When I try to create a new tutorial from “Postman” it is showing me the error:
ReferenceError: Cannot access ‘Task’ before initialization
Any solution for this?
Hi,
nice tutorial, but im locked here :
TypeError: db.mongoose.connect is not a function
at Object.
index.js :
Hi, instead of
db.mongoose = db;
in your code, you should write:db.mongoose = mongoose;
the url is in ‘./config/db.config.js’, so you need to define the db as following:
const db = require(‘./config/db.config.js’);
otherwise the connection cannot be established.
Hey!!!Very nice tutorial and very much helpful..
One thing i would like to have is i want to send a multiple data as json.
Like:-
[
{
“title”: “HTML”,
“description”: “UI”
},
{
“title”: “Javascript”,
“description”: “Scripting Language”,
},
{
“title”: “Angular”,
“description”: “Framework”,
}
]
how this feature can be implemented??
Hi, you can use Model.insertMany().
Thank You Bro. Its Awesome.
Thank you
no need to use “mongoose.Promise = global.Promise;” anymore in mongoose 5….
thanks for this wonderful tutorial
i have i ssue when i try to search with id
Eror Message:
Cannot GET /api/tutorials/5ec7c48900ba2804d0b29ca6
Thanks
I caught my error…
Regards
Nikhil
What was your error plz
Why are you showing me this error?
{
“message”: “Cast to ObjectId failed for value \”published\” at path \”_id\” for model \”Tutorial\””
}
The solution I found was modifying my routes file:
From this:
To this:
But if I want to know what is the reason for this error. Thanks
Awesome tutorials. Thank you sir 🐤
Really, really cool way to structure things. Very efficient and maintainable as the codebase grows. Thank you for this!!
Nice tutorial
its great tutorial, but ive some problem :
TypeError: Tutorial.find is not a function
at exports.findAll (D:\Faisal\web\Dev\nem-api\app\controllers\tutorial.controller.js:36:14)
at Layer.handle [as handle_request] (D:\Faisal\web\Dev\nem-api\node_modules\express\lib\router\layer.js:95:5)
at next (D:\Faisal\web\Dev\nem-api\node_modules\express\lib\router\route.js:137:13)
at Route.dispatch (D:\Faisal\web\Dev\nem-api\node_modules\express\lib\router\route.js:112:3)
at Layer.handle [as handle_request] (D:\Faisal\web\Dev\nem-api\node_modules\express\lib\router\layer.js:95:5)
at D:\Faisal\web\Dev\nem-api\node_modules\express\lib\router\index.js:281:22
at Function.process_params (D:\Faisal\web\Dev\nem-api\node_modules\express\lib\router\index.js:335:12)
at next (D:\Faisal\web\Dev\nem-api\node_modules\express\lib\router\index.js:275:10)
at Function.handle (D:\Faisal\web\Dev\nem-api\node_modules\express\lib\router\index.js:174:3)
at router (D:\Faisal\web\Dev\nem-api\node_modules\express\lib\router\index.js:47:12)
at Layer.handle [as handle_request] (D:\Faisal\web\Dev\nem-api\node_modules\express\lib\router\layer.js:95:5)
at trim_prefix (D:\Faisal\web\Dev\nem-api\node_modules\express\lib\router\index.js:317:13)
at D:\Faisal\web\Dev\nem-api\node_modules\express\lib\router\index.js:284:7
at Function.process_params (D:\Faisal\web\Dev\nem-api\node_modules\express\lib\router\index.js:335:12)
at next (D:\Faisal\web\Dev\nem-api\node_modules\express\lib\router\index.js:275:10)
at urlencodedParser (D:\Faisal\web\Dev\nem-api\node_modules\body-parser\lib\types\urlencoded.js:91:7)
Hi, please make sure that you write code in app/models/index.js correctly.
wahoo very clear, thanks.
question :
do you have any tutorial on nodejs+express+vuejs+cassandra?
if yes please share the link
Hi, I will write the tutorial when having time. Thanks for your suggestion.
Thank you for this tutorial. I’ve just started learning node.js and it helps me a lot to see how a basic app is set up.
hello please i need your help: i got this from postman
{
“message”: “Content can not be empty!”
}
how can i solve it
Hi, maybe you forgot to set
Content-Type: application/json
🙂change the type in the POST MAN from Text to JSON type and it will work fine
Awesome post! Congratulations.
error cannot find module ‘./app/routes/tutorial.routes.js’
bezkoder hep me
It is
turorial.routes.js
with letter ‘R’, just a typo 🙂Hi, would you like to make video instruction for this tutorial?
Yeah, I’ve just created a Youtube video. You can find it here:
https://www.youtube.com/watch?v=73vNuCv8kzA
an error cannot find module ‘./app/routes/tutorial.routes.js’
plz help me, anyone
It is
turorial.routes.js
with letter ‘R’, just a typo 🙂it’s ok now I found the issue
hello I did everything as in tutorial, I get connected to the database and everything, but when I test in Postman I get this error: Cannot POST /api/tutorials
the same for other API test
Maybe you didn’t set Content Type for Http Request header 🙂
I am facing the same problem. How did you correct it Sir?
Hi, please make sure that you’ve set
Content-Type : application/json
in HTTP request header (Postman Header tab).For learning
Thanks for the tutorial!
Every time I try to create a “new tutorial”, postman return “Content can not be empty”. As a last try , i’ve downloaded the project from github, I still have the same issue . I have no idea left as to where to check
Hi, please make sure that you’ve set
Content-Type : application/json
in HTTP request header (Postman Header tab).Hello!
First, thank you for the tutorial!
Every time I try to create a “new tutorial”, postman return “Content can not be empty”.
I’ve triple checked that I wrote “title” as title everywhere and it seems that way. I’m a bit at lost as to where to look next ?
change the type in the POST MAN from Text to JSON type and it will work fine
hola tengo el mismo error pero ahora me pone
{
“message”: “Operation `tutorials.insertOne()` buffering timed out after 10000ms”
}
When I try to do an update, the message is ok “Updated successfully”, but no changes is done in the database – where should I look for the problem?
Found it, was sending the update as text instead of JSON.
//Kjell
Hi, everything works correctly in frontend but backend codes do not work for me.
Hi, what’s wrong?
“TypeError: db.mongoose.connect(…).then is not a function” can you help me?
Hi, please check app/models/index.js file, make sure that you’ve initialized
mongoose
correctly.Thank you, man!
Awesome post!
PS: There is a typo in ‘turorial.routes.js’ filename, i’ve created it like tutorial but copied your code and a error appeared that tutorial.routes.js file is not found. It took me a couple of minutes to find out that the problem is in tuRorial))
Ah yeah, thank you for telling me the typo 🙂
Hello, I am new to Rest api, How to write a update and find query in a nested collection?
great same here then I just about to stop further on this example and I read your comment.