I will write the code in expressjs (i.e framework of nodejs).
Before writing the the code make sure you have installed -
- nodejs- https://nodejs.org/en/download/
- mongodb-https://www.mongodb.com/download-center/community
- Visual studio or any other code writting software - https://code.visualstudio.com/download
- Open cmd in visual studio code by pressing ( ctrl + ` ) then type in cmd -
npm init
- Then install the dependencies by trying the command-
npm install express mongoose - Then make two file named as server.js and User.js
1- server.js
- const express = require('express');
- const mongoose = require('mongoose');
- const User = require('./User.js'); // write User.js file path
- const app = express();
- mongoose.connect('mongodb://localhost/dbname', { useNewUrlParser: true})
- .then( console.log('connected to mongoose') )
- .catch( err => { console.log(err) } )
- app.get('/', (req,res) => {
- User.find()
- .then(users => {
- res.json(users);
- })
- })
- app.listen(3000);
2- User.js
- const mongoose = require('mongoose');
- const Schema = mongoose.Schema;
- const UserSchema = new Schema({
- name: {
- type:string,
- required:true
- },
- email: {
- type:string,
- required:true
- },
- password: {
- type:string,
- required:true
- }
- })
- module.exports = User = mongoose.model ('user', UserSchema);
- After writing this code, type in cmd -
node server.js - Then go to the browser and type localhost:3000 in url.
You will fetch the data of users from your database which you have made.
Initially your database will be empty so go to C:\Program Files\MongoDB\Server\4.0\bin
where you have installed mongodb and open mongo.exe file.
where you have installed mongodb and open mongo.exe file.
- After running the above code database with name dbname will be automatically made with collection name as users.
- So simply write the command in mongo.exe as- use dbname to enter the database.
- And finally write the command to insert items as -
db.users.insert({name: 'John', email:'john@gmail.com', password:'john'})
Now reload the page of browser and you will see the user details in JSON format.
Enjoy :)
You can also visit -
Simple code for storing images coming from the frontend to Node.js using Mongoose?
Enjoy :)
You can also visit -
Simple code for storing images coming from the frontend to Node.js using Mongoose?
I hope this will help.
Fell free to ask any doubt :)
Fell free to ask any doubt :)
0 Comments