猫鼬没有保存儿童文件

时间:2017-07-02 15:00:26

标签: javascript mongodb typescript mongoose insert

我正在尝试插入到我的集合中,它确实插入了,但是子文档没有被保存,我不知道为什么。

我有计划/模型

import { Schema, Document, Model, model } from 'mongoose'

export interface IPerson {
  name: {
    first: string
    last: string
  }
  dob: Date
}

export interface IPersonModel extends IPerson, Document { }

let nameSchema: Schema = new Schema({
  first: String,
  last: String
})
let PersonName = model('PersonName', nameSchema)

export var personSchema: Schema = new Schema({
  name: { child: PersonName.schema },
  dob: Date
}, { timestamps: true })

export const Person: Model<IPersonModel> = model<IPersonModel>('Person', personSchema, 'people')

我使用express传递数据并使用模型,如下所示:

import * as bodyParser from 'body-parser'
app.use(bodyParser.json())

app.post('/save/:type', async (req, res) => {
  if (!req.xhr) res.sendStatus(400)
  let p = new Person({
    name: {
      first: req.body.first,
      last: req.body.last
    },
    dob: new Date()
  })
  p.save((err, data) => {
    if (err) console.log(err);
    else console.log('Saved : ', data);
  })
  res.sendStatus(200)
})

当我保存时,我得到以下输出到终端:

Saved :  { __v: 0,
    updatedAt: 2017-07-02T14:52:18.286Z,
    createdAt: 2017-07-02T14:52:18.286Z,
    dob: 2017-07-02T14:52:18.272Z,
    _id: 595908a27de708401b107e4b 
}

那么,为什么我的孩子name没有得救?

1 个答案:

答案 0 :(得分:0)

好的,我需要做的就是将child更改为type,如下所示:

name: { child: PersonName.schema }

name: { type: PersonName.schema }

通过传递模式,这也创建了一个_id,所以我能够通过传递一个模式来改变它,只需传递一个这样的对象:

name { type: { first: String, last: String } }
相关问题