我正在尝试插入到我的集合中,它确实插入了,但子文档没有保存,我不确定为什么。
我有这个方案/模型:
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
}
那么,为什么我的 child name
没有被保存?
最佳答案
好的,所以我需要做的是将 child
更改为 type
,如下所示:
name: { child: PersonName.schema }
至
name: { type: PersonName.schema }
通过传递架构,这还会创建一个 _id
,因此我能够通过传递一个对象来更改它,而不是传递架构,如下所示:
name { type: { first: String, last: String } }
关于javascript - Mongoose 不保存子文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44872174/