猫鼬Model.save()仅返回{_id,__v}

时间:2020-07-02 19:06:43

标签: javascript node.js mongodb express mongoose

我知道之前曾有人问过这个问题,但我觉得我做对了所有事情,但仍然遇到问题。我想使用猫鼬将表单中的项目保存到我的mongodb集合中。

我的模式:

// stationmodel.js
export 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.js
const 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.js
import 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 个答案:

答案 0 :(得分:3)

您正在将es6模块import/export与Node.js CommonJS require混合在一起。

stationmodel.js中,您使用的是“命名导出”

export const StationSchema = new mongoose.Schema(...

但是在routes.js中,您使用的是CommonJS require

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')