2017-07-02 172 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 } }