2017-07-02 117 views
1

我想插入到我的集合中,它插入,但子文档没有保存,我不知道为什么。猫鼬不保存子文档

我有这个方案/模式

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

我使用快递在数据传递和使用模式像这样:

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没有得到保存?

回答

0

好了,所以我需要做的是改变childtype像这样:

name: { child: PersonName.schema } 

name: { type: PersonName.schema } 

通过传递一个模式,这也创造了一个_id,所以我能通过而不是传递模式来改变这种情况,只需传递如下对象:

name { type: { first: String, last: String } }