我知道以前有人问过这个问题,但我觉得我做的一切都是正确的,但我仍然遇到问题。我想使用 mongoose 将表单中的项目保存到我的 mongodb 集合中。我的架构:// stationmodel.jsexport const StationSchema = new mongoose.Schema({ "FDID": String, "Fire dept name": String, "HQ addr1": String, "HQ city": String, "HQ state": String, "HQ zip": Number, "HQ phone": String, "Dept Type": String, "Organization Type": String, "Website": String, "Number Of Stations": Number, "Primary agency for emergency mgmt": Boolean,}, {collection: "FEMA_stations"}) 在我的快递应用程序中:// in routes.jsconst StationSchema = require('./stationmodel')const Station = mongoose.model('Station', StationSchema, 'FEMA_stations')const addstation = (req, res) => { console.log(req.body) const newStation = new Station(req.body) newStation.save( function(err){ if (err) { console.error(err) } console.log('newStation after save', newStation) })}const routes = app => { app.route('/api/addstation') .post(addstation)}export default routes// in index.jsimport routes from './routes'app.use(bodyParser.urlencoded({ extended: true }))app.use(bodyParser.json())routes(app)在我的前端代码中,在 redux 操作中调用后端:fetch('/api/addstation', { method: "POST", headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(stationToAdd)})当我console.log(req.body)在后端时,我得到了我期望的数据。它看起来像这样:{ FDID: '202020', 'Fire dept name': 'Some Fire Department', 'HQ addr1': 'Some address', 'HQ city': 'San Dimas', 'HQ state': 'CA', 'HQ zip': 99999, 'HQ phone': '5555555555', 'Dept Type': 'Career', 'Organization Type': 'State', Website: '', 'Number Of Stations': 0, 'Primary agency for emergency mgmt': true,}但是当我console.log尝试newStation这样做时.save(),我得到的只是这样的回应:{ _id: 5efe29911ea067248f3c39a0, __v: 0 }我知道其他人的架构、模型存在问题,确保他们真正连接到他们的 mongodb 集合,或者确保请求是使用application/json标头发出的,但我觉得我所有这些都是正确的。该代码是从一个更加模块化的应用程序中拼凑而成的,以尝试减少脂肪并提出核心问题,所以如果我遗漏了任何明显的信息,请告诉我。这里可能出了什么问题?req.body为什么我试图保存到集合中的数据没有进入我的新文档?谢谢阅读。
1 回答
PIPIONE
TA贡献1829条经验 获得超9个赞
您正在将 es6 模块import/export与 Node.js CommonJS混合require。
在stationmodel.js您正在使用“命名导出”
export const StationSchema = new mongoose.Schema(...
但是在routes.js你使用 CommonJSrequire
const StationSchema = require('./stationmodel')这很可能是一个空对象。因此,以下行将创建一个具有“空”模式的模型
const Station = mongoose.model('Station', StationSchema, 'FEMA_stations')解决方案
import改用命名
import { StationSchema } from './stationmodel'小费:
由于您已经为文件命名stationmodel.js,这表明它是一个模型。您可以直接放入以下内容stationmodel.js以防止模型获取不正确的架构
export const Station = mongoose.model('Station', StationSchema, 'FEMA_stations')添加回答
举报
0/150
提交
取消
