skip to Main Content

I want to save data in mongodb, so i made an open schema. after post request it is getting uploaded in my database. but only objectid is shown in the database. I’m new to mongodb and even node, so i cannot pinpoint where my mistake is..

// <---------server.js  ------->

const http = require('http')
const express = require ('express')
const mongoose = require('mongoose')
// const router = require('./routes/hello')

const app = express();

// app.use(router)

app.use('/api', require('./routes/hello'))
 app.use('/api2', require('./routes/data'))


const MONG0_URL =  'mongodb+srv://aftrn:[email protected]/?retryWrites=true&w=majority';


const PORT = process.env.PORT || 8000 ;

const server = http.createServer(app)


mongoose.connection.on('open', ()=>{
    console.log("Mongoose is ready !!")
})
mongoose.connection.on('error', (err)=>{
    console.log(err)
})






 function startServer(){
     mongoose.connect(MONG0_URL , {
        useNewUrlParser : true,
        useUnifiedTopology : true ,
    })
    server.listen(PORT,()=>{
        console.log('listening to port')
    })
}

startServer();
// <-------------data.js-------------->

var Router = require('router')
var mongoose = require('mongoose')
var express  = require('express')

var router = Router()


//schema 

const sch = 
   {
      name : String,
      email : String
     }


const monmodel = mongoose.model("aftrn col", sch) 
router.post('/obj2', async function(req,res){
 console.log("inside post fn")
   const data = new monmodel({
     name : req.body,
     email : req.body,
   })
  

const val = await data.save();  //saves data in collection
res.json(val);
console.log("data is stored")
 })

module.exports = router ;

my input to postman >

{
    "name" : "bobby again ",
    "email" : " bobbyagain@lfc"
}

what I’m getting as output >

{
    "_id": "632464434727474bed2a831f",
    "__v": 0
}

Thank you really appreciate the help.

2

Answers


  1. you are not creating schema. you need to write
    const schema=new mongoose.Schema({ name : String, email : String})

    Login or Signup to reply.
  2. For post you need bodyparser

    app.use(express.json())

    Change this

    const data = new monmodel({
         name : req.body,
         email : req.body,
       })
    

    to

    const data = new monmodel({
         name : req.body.name,
         email : req.body.email,
       })
    

    In Server.js

    var express = require('express');
    
    var app = express();
    
    app.use(express.json());  // <----- here add post middleware
    ....
    ....
    module.exports = app;
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search