javascript - Mongoose 不保存子文档

标签 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 
}

那么,为什么我的 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/

相关文章:

javascript - jQuery - 通过元素的 data-for 属性将 .html() 设置为元素

javascript - 如何在 GSAP 或 Javascript 中以不同的时间间隔调用函数?

javascript - 通过 ng-repeat 中的键过滤对象

typescript - 如何在Typescript中将类和接口(interface)分离到同一命名空间下的单独文件中

angular - 如何在我的 Angular 12 应用程序中实现 firebase app-check

javascript - 将一组对象复制到javascript中的另一个数组中(深度复制)

javascript - 找不到模块 : Error: Can't resolve 'dns' when using MongoDB

mongodb - 是否可以使用 mgo 驱动程序运行 mongo replicaset 命令?

java - 在 mongodb 中执行 isMaster 命令时出现异常

typescript - 在 TypeScript 中复制同键属性错误