create collection of models in nodejs app
create a table in mongodb
create personSchema,js in models app
var mongoose= require("mongoose");
const PERSON_SCHEMA = new mongoose.Schema(
{
fname:{type:String},
lname:{type:String},
mno:{type:String},
addr:{type:String},
}
)
module.exports = mongoose.model("persons",PERSON_SCHEMA);
import mongoose
write schema
export this schema
after write this schema
insert data into table using api post create method
let bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
var PERSON_SCHEMA=require("./models/personSchema,js");
app.post('/create',async (req, res, next)=> {
let body = req.body;
let new_body={
fname: body.firstname,
lname: body.lastname,
mno: body.mobilenum,
addr:body.address
}
let new_person = new PERSON_SCHEMA(new_body);
new_person.save().then(result =>
{
res.send("success")
}).catch(err => {
res.send("faile")
})
})
ist import this schema into third.js file
and
create api post method
name is create
get data from api or postman
if u send like this -> it wil show sucess on api output
after sucesfful
in atabse if not created databse - it will create
if not createc collection, it will create collection
third.js
const express = require('express');
const app = express();
var user_routing= require("./controller/usercontroller");
var role_routing= require("./controller/rolecontroller");
var PERSON_SCHEMA=require("./models/personSchema,js");
var mongoose= require("mongoose");
mongoose.connect('mongodb://localhost:27017/mydatabase' ,
{
useNewUrlParser: true,
useUnifiedTopology: true
})
.then((res) => {
console.log(
'connected'
);
})
.catch((err) => {
console.log(
`not connected`,
err
);
});
let bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.post('/create',async (req, res, next)=> {
let body = req.body;
let new_body={
fname: body.firstname,
lname: body.lastname,
mno: body.mobilenum,
addr:body.address
}
let new_person = new PERSON_SCHEMA(new_body);
new_person.save().then(result =>
{
res.send("success")
}).catch(err => {
res.send("faile")
})
})
const PORT=3000;
app.use(express.json());
app.use("/user",user_routing);
app.use("/role",role_routing);
app.listen(PORT,() =>
{
console.log("server on::"+PORT)
})
models/personschema.js
var mongoose= require("mongoose");
const PERSON_SCHEMA = new mongoose.Schema(
{
fname:{type:String},
lname:{type:String},
mno:{type:String},
addr:{type:String},
}
)
module.exports = mongoose.model("persons",PERSON_SCHEMA);
No comments:
Post a Comment