Mongoose 实例未保存到数据库,未显示错误
Posted
技术标签:
【中文标题】Mongoose 实例未保存到数据库,未显示错误【英文标题】:Mongoose Instance not saving to the database,no error is being shown 【发布时间】:2019-12-02 06:47:35 【问题描述】:我正在尝试将模型保存到 mongodb。虽然它没有显示任何错误,但实例没有被保存到 db。对象正在正确填充,您可以看到控制台的输出。可能是什么问题?
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')
)
)
模型中addHosp函数中console.log的输出:
_id: 5d3806a53b0d4215ac6bac53,
name: 'h',
specialization: 's',
location: 'l',
pointOfContact:
[ _id: 5d3806a53b0d4215ac6bac54, name: 'n', phone: '99999' ]
【问题讨论】:
试试 hospital.save();,没有回调.. hospital.save() 没有解决问题,但告诉我错误在哪里。谢谢。所以发生错误是因为我没有从前端正确传递医院地址。 我很高兴你能解决这个问题...... :) 【参考方案1】:像这样更新你的函数:
module.exports.addHospital = function(hospital,callback)
var hosp = new Hospital(hospital)
console.log(hosp);
hosp.save(callback);
【讨论】:
以上是关于Mongoose 实例未保存到数据库,未显示错误的主要内容,如果未能解决你的问题,请参考以下文章
集合未保存在 mongodb 中(来自 mongoose 填充文档的故事集合)
Mongoose VersionError:保存文档时未找到与 id 匹配的文档