23
loading...
This website collects cookies to deliver better user experience
{
"todo": [
{
"_id": "61023642610b8d4ce4f56f81",
"title": "test-title-1",
"description": "test-description-1",
"__v": 0
},
{
"_id": "6102365b610b8d4ce4f56f84",
"title": "test-title-2",
"description": "test-description-2",
"__v": 0
}
],
"_id": "6102361f610b8d4ce4f56f7f",
"name": "test-user",
"__v": 0
}
User
schema is referencing the Todo
schema. To get the JSON data with the todo
data we need to do the followingObjectId
of the new todo
to the todo
array of the User
. At this stage the data will look something like this.
{
"todo": ["61023642610b8d4ce4f56f81", "6102365b610b8d4ce4f56f84"],
"_id": "6102361f610b8d4ce4f56f7f",
"name": "test-user",
"__v": 0
}
Todo
table using the populate
method which will get the data of the todo
.SQL
where User
table references the Todo
table using the primary key
of the Todo table
. Here, the primary key
of the Todo table
is the ObjectId
.npm
and install necessary packages.Node
and Express
.Todo
.create
user and todo and read
user and todo.API
routes using Insomnia.VS Code
or any other editorNode.js
Insomnia
or PostmanPrettier
VS code extension to format the codenpm init -y
package.json
if the folder.npm i cors dotenv express mongoose
cors
: allows cross-origin api callsdotenv
: needed to access data from .env
filesexpress
: web application framework for node.jsmongoose
: It is needed to define the database schema and connecting to mongoDB
-D
is used to install the development dependencies.npm i -D nodemon
package.json
folder should look as follows.// package.json
{
"name": "mongodb-schema-populate-blog",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"repository": {
"type": "git",
"url": "git+https://github.com/mritunjaysaha/mongodb-schema-populate-blog.git"
},
"keywords": [],
"author": "",
"license": "ISC",
"bugs": {
"url": "https://github.com/mritunjaysaha/mongodb-schema-populate-blog/issues"
},
"homepage": "https://github.com/mritunjaysaha/mongodb-schema-populate-blog#readme",
"dependencies": {
"dotenv": "^10.0.0",
"express": "^4.17.1",
"mongoose": "^5.13.3"
},
"devDependencies": {
"nodemon": "^2.0.12"
}
}
server.js
file and a .env
. The server.js
file will be the entry point of the server and the .env
file will contain the MONGO_URI
. We also have to make the following changes in the package.json
//package.json
{
"name": "mongodb-schema-populate-blog",
"version": "1.0.0",
"description": "",
"main": "server.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"repository": {
"type": "git",
"url": "git+https://github.com/mritunjaysaha/mongodb-schema-populate-blog.git"
},
"keywords": [],
"author": "",
"license": "ISC",
"bugs": {
"url": "https://github.com/mritunjaysaha/mongodb-schema-populate-blog/issues"
},
"homepage": "https://github.com/mritunjaysaha/mongodb-schema-populate-blog#readme",
"dependencies": {
"dotenv": "^10.0.0",
"express": "^4.17.1",
"mongoose": "^5.13.3"
},
"devDependencies": {
"nodemon": "^2.0.12"
}
}
config
: Inside the config
folder, create a file named db.js
. This file will contain the required code for connecting to the MongoDB
database.
controllers
: The controllers
folder will contain the files which will have the methods for the end points to communicate with the database.
models
: The models
folder, will contain the files which will define the MongoDB schema
routers
: The routers
folder will contain the files with the endpoints
.
.
├── config
│ └── db.js
├── controllers
│ └── user.js
├── models
│ ├── todo.js
│ └── user.js
├── node_modules
├── routes
│ └── user.js
├── .env
├── server.js
├── package-lock.json
└── package.json
"scripts": {
"start":"node server.js",
"dev":"nodemon server.js"
}
package.json
file should look as follows{
"name": "mern-todo",
"version": "1.0.0",
"description": "",
"main": "server.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node server.js", //added
"dev": "nodemon server.js" //added
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"config": "^3.3.6",
"cors": "^2.8.5",
"dotenv": "^10.0.0",
"express": "^4.17.1",
"mongoose": "^5.13.2"
},
"devDependencies": {
"nodemon": "^2.0.12"
}
}
express
express()
get
method for the endpoint http://localhost:8000
using app.get()
PORT
to 8000
for our server to runPORT
using app.listen()
.
├── config
│ └── db.js
├── controllers
│ └── user.js
├── models
│ ├── todo.js
│ └── user.js
├── node_modules
├── routes
│ └── user.js
├── .env
├── server.js <-- we are here
├── package-lock.json
└── package.json
nodemon
using the following code. Make sure you are running the following command from the project directory.npm run dev
[nodemon] 2.0.11
[nodemon] to restart at any time, enter `rs`
[nodemon] watching path(s): *.*
[nodemon] watching extensions: js,mjs,json
[nodemon] starting `node server.js`
server is running on http://localhost:8000
http://localhost:8000
on your browser.mongoDB
collection.allow access from anywhere
. Then Add IP address
//.env
MONGO_URI = mongodb+srv://<username>:<password>@cluster0.owmij.mongodb.net
<username>
and <password>
with your database username and password which you will set in step 9..
├── config
│ └── db.js <-- we are here
├── controllers
│ └── user.js
├── models
│ ├── todo.js
│ └── user.js
├── node_modules
├── routes
│ └── user.js
├── .env
├── server.js
├── package-lock.json
└── package.json
db.js
file which is in the config
folder and add the following changes.mongoose
MONGO_URI
from .env
connectDB
methof for connecting to the databaseconnectDB
method to be called in server.js
server.js
file.dotenv
connectDB
method from config/db.js
connectDB
method.server.js
npm run dev
. The terminal should show a message of MongoDB is connected
which we have added in the db.js
under the try block.todo.js
file in the models folder. We will define the database schema in this file..
├── config
│ └── db.js
├── controllers
│ └── user.js
├── models
│ ├── todo.js <-- we are here
│ └── user.js
├── node_modules
├── routes
│ └── user.js
├── .env
├── server.js
├── package-lock.json
└── package.json
mongoose
Schema
called TodoSchema
title
and description
title
will be String
and it is a mandatory fielddescription
will be String
and it is not a mandatory field.
├── config
│ └── db.js
├── controllers
│ └── user.js <-- we are here
├── models
│ └── todo.js
├── node_modules
├── routes
│ └── user.js
├── .env
├── server.js
├── package-lock.json
└── package.json
Todo
and User
schemascreateUser
method will create a new usercreateTodo
method will do the following
userId
to find the usertodo
array with the ObjectId
of the new todogetUser
to get the user details. The output of this method we can see that todo
consists of some random value which is the ObjectId
of the todo
that the user has created. We cannot figure out what the todo contains.
{
"todo": ["61023642610b8d4ce4f56f81", "6102365b610b8d4ce4f56f84"],
"_id": "6102361f610b8d4ce4f56f7f",
"name": "test-user",
"__v": 0
}
getAllTodo
method we will use the userId
to find the user and then use the populate
method to reference the todo
with the ObjectId
from the Todo
table. The exec
method is used to check for errors and return the populated data.
{
"todo": [
{
"_id": "61023642610b8d4ce4f56f81",
"title": "test-title-1",
"description": "test-description-1",
"__v": 0
},
{
"_id": "6102365b610b8d4ce4f56f84",
"title": "test-title-2",
"description": "test-description-2",
"__v": 0
}
],
"_id": "6102361f610b8d4ce4f56f7f",
"name": "test-user",
"__v": 0
}
.
├── config
│ └── db.js
├── controllers
│ └── user.js
├── models
│ └── todo.js
├── node_modules
├── routes
│ └── user.js <-- we are here
├── .env
├── server.js
├── package-lock.json
└── package.json
create
users and todo and to read
them.express
controllers
router
POST
method to create
a userPOST
method to create
a todo and save it in the userGET
method to read
user dataGET
method to read
user data and todo data.
├── config
│ └── db.js
├── controllers
│ └── todo.js
├── models
│ └── todo.js
├── node_modules
├── routes
│ └── todo.js
├── .env
├── server.js <-- we are here
├── package-lock.json
└── package.json
server.js
file.routes/todo.js
POST
request to http://localhost:8000/api/user
POST
request to http://localhost:8000/api/user/todo/:userId
_id
from the response of the create a user request
GET
request to http://localhost:8000/api/user/:userId
POST
request to http://localhost:8000/api/user/todo/:userId