版本号
mongoose是最新版↓
"mongoose": "^7.1.0",
问题描述
- mongoose创建文档时,子文档有默认值,创建后子文档无效,如下↓
import mongoose from "mongoose"
const readWriteUrl = 'mongodb://127.0.0.1:27017/jxz'
const db = mongoose.connect(readWriteUrl)
const mg = await db
const { Schema } = mg
const 父级 = mg.model('users', new Schema({ // 父文档
age: {
type: Number,
default: 0,
},
// 子文档
info: new Schema({
name: {
type: String,
default: '默认昵称'
},
sex: {
type: Number,
default: 0,
}
})
}))
const 创建父级文档 = await new 父级().save()
console.log(创建父级文档);
运行结果
数据库
上图所示,子文档没有被创建
解决子文档未创建
-
官网介绍 - https://mongoosejs.com/docs/subdocs.html
-
子文档对象有2属性,分别为↓
- type
- 值:Schema
- default
- 值:
() => ({})
箭头函数
- 值:
- type
码↓
import mongoose from "mongoose"
const readWriteUrl = 'mongodb://127.0.0.1:27017/jxz'
const db = mongoose.connect(readWriteUrl)
const mg = await db
const { Schema } = mg
const 父级 = mg.model('test', new Schema({ // 父文档
age: {
type: Number,
default: 0,
},
// 子文档
info: {
// 重点1 ,子文档的type是Schema
type: new Schema({
name: {
type: String,
default: '默认昵称'
},
sex: {
type: Number,
default: 0,
}
}),
// 重点2,默认值为箭头函数
default: () => ({})
}
}))
const 创建父级文档 = await new 父级().save()
console.log(创建父级文档);
解决结果
运行结果
数据库