After trying to insert into my collection, I noticed that the sub-document is not being saved along with it. This issue has left me puzzled.
This is the scheme/model I am working with:
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')
To pass in data using express and utilize the model, my code looks like this:
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)
})
Upon saving, the following output is displayed on the terminal:
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
}
Despite this, the child section of name
remains unsaved. What could be causing this issue?