简体   繁体   中英

Mongoose Instance not saving to the database,no error is being shown

I'm trying to save a model to mongodb. Although it's not showing any error,the instance is not being saved to db.The object is being properly populated as you can see the output of console.What could be the issue?

Model
------
const mongoose = require('mongoose');
const config = require('../config/database');
const HospitalSchema = mongoose.Schema({
    name:{type:String,required:true},
    specialization:{type:String,required:true},
    location:{type:String,required:true},
    address:{type:String,required:true},
    pointOfContact:[{
        name:{type:String,required:true},
        phone:{type:String,required:true}
    }]
})
const Hospital = module.exports = mongoose.model('Hospital',HospitalSchema);
module.exports.addHospital = function(hospital,callback){
    console.log(hospital);
    hospital.save(callback);
}


controller
----------
router.post('/hospital/addHosp',(req,res)=>{
  console.log(req.body);
  let hospital = new Hospital({
    name:req.body.hosp.name,
    specialization:req.body.hosp.specialization,
    location:req.body.hosp.location,
    address:req.body.hosp.completeAddress,
    pointOfContact:req.body.hosp.pointOfContact,
});

Hospital.addHospital(hospital,(err,hosp)=>{
  (err)=>{console.log(err);res.json({success:false,msg:'failed to add hospital'})},
  (hosp)=>{res.json({success:true,msg:'successfully added hospital'})}
})

})

The output of console.log in addHosp function in model:

{ _id: 5d3806a53b0d4215ac6bac53,
  name: 'h',
  specialization: 's',
  location: 'l',
  pointOfContact:
   [ { _id: 5d3806a53b0d4215ac6bac54, name: 'n', phone: '99999' } ] }

Update your function like this one:

module.exports.addHospital = function(hospital,callback){
    var hosp = new Hospital(hospital)
    console.log(hosp);
    hosp.save(callback);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM