I am new to node and mongoDb, I have a mongo db account where i created a collection called "dbTestData"
I am trying to create CRUD operation using node express mongoose and express, and i am using postman to get post update and delete values to mlab db.
My Get call is working fine, but when i try to post values in Json like,
i am getting success message , but when i check the db it is saved as
{
"_id": {
"$oid": "5c3ad1c19bc5932f800d26f7"
},
"__v": 0
}
My app.js
const express = require('express');
const bodyParser = require("body-parser");
const mongoose=require('mongoose');
const app = express();
const dbTestData=require('./models/post')
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
mongoose.connect("mongodb://<userName>:<password>@ds221242.mlab.com:21242/kiitasklist").then(()=>{
console.log("hello");
}).catch(
()=>{
console.log("heee");
});
app.use((req, res, next) => {
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader(
"Access-Control-Allow-Headers",
"Origin, X-Requested-With, Content-Type, Accept"
);
res.setHeader(
"Access-Control-Allow-Methods",
"GET, POST, PATCH, PUT,DELETE, OPTIONS"
);
next();
});
app.post("/api/posts", (req, res, next) => {
const post = new dbTestData({
id:req.body.id,
name:req.body.name
});
post.save().then(documents=>{
console.log(post);
res.status(201).json({
message: 'Post added successfully'
});
});
});
app.get("/api/posts",(req,res,next)=>{
dbTestData.find().then(documents=>{
res.status(200).json({
message:'Posts fetched successful',
posts:documents
});
});
});
app.put("/api/posts/:id",(req,res,next)=>{
const post = new dbTestData({
_id:req.body._id,
name:req.body.name
});
dbTestData.updateOne({_id:req.params.id},post).then(result=>{
res.status(200).json({message:"update successfully"});
});
});
app.delete("/api/posts/:id",(req,res,next)=>{
dbTestData.deleteOne({_id:req.params.id}).then(documents=>{
res.status(200).json({
message:'posts fetched successful',
posts:documents
});
});
});
module.exports = app;
My Server.js
const http = require('http');
const app = require('./api/app');
const port = process.env.PORT || 3000;
const server = http.createServer(app);
server.listen(port);
My post.js where i have created the mongoose schema
const mongoose=require('mongoose');
var Schema = mongoose.Schema;
module.exports= mongoose.model("dbTestData", new Schema({}), "DbTestData");
both the get and delete works , But the post and put is not happening properly, it returns a success message in my console but empty value like
{
"_id": {
"$oid": "5c3ad1c19bc5932f800d26f7"
},
"__v": 0
}
is saved during POST and nothing happens during PUT.
To solve this post issue
var Schema = mongoose.Schema;
PostSchema = new Schema({
id:Number,
name: String
});
// the compile the model using mongoos model function giving the schema u created
const Post = module.exports= mongoose.model("dbTestData", PostSchema, "DbTestData");
after that in your post req do it like this
//before posting you need to require the model first
const Post = require('./models/post'); // your post.js
app.Post("/api/posts", (req, res, next) => {
const post = new Post({
id:req.body.id,
name:req.body.name
});
post.save().then(documents=>{
console.log(post);
res.status(201).json({
message: 'Post added successfully'
});
});
});
make sure you create/define your schema correctly in order to save data using it. after that put is the same the way u did it should work fine after u define your schema correctly
and finally try this also. make sure you add these tow line the exact same way I have given in your case you have made them switched
// Body Parser Middleware
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());