如何向 Mongoose 模式添加新键?
How do I add new keys to a Mongoose Schema?
我最近开始为我的高级项目开发一个应用程序,它需要我使用某种类型的数据库。为此,我决定使用 Mongoose,因为它是 noSQL 并且更容易上手。
所以,快进,我 运行 遇到了一个问题,我无法弄清楚如何编辑现有架构并向其中添加新键。
例如,我有一个代表 post(想想 Tweets 或 Facebook posts)的架构,其中包含:
- 包含 post
正文的字符串
- 创建 post
的用户 ID
- 创建 post 的日期
我的代码是:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
// Create Schema
const PostsSchema = new Schema({
Value: {
type: String,
required: true
},
User: {
type: Schema.Types.ObjectId,
ref:'users'
},
Date: {
type: Date,
default: Date.now
}
});
// Create collection and add schema
mongoose.model('posts', PostsSchema, 'posts');
我现在想要的是以某种方式访问该架构并使用类似于
的方式向其添加新密钥
PostsSchema.add({Private: { default: false}});
这意味着,现在数据库中的架构将类似于:
{
"_id": {
"$oid": "1831g98af21n9s5u7s9ccchj5"
},
"Value": "Beautiful day outside, can't wait to go jogging!",
"User": {
"$oid": "9a79ab143lbk9lk55wq327oi3226m"
},
"Date": {
"$date": "2018-10-29T01:28:44.408Z"
},
"Private": "false"
"__v": 0
}
所以回到我的问题,有什么办法可以做到这一点?或者,如果您有 link 此类方法的文档,我将不胜感激。非常感谢!
只需使用 default
:
将字段添加到架构中
const PostsSchema = new Schema({
Value: {
type: String,
required: true
},
User: {
type: Schema.Types.ObjectId,
ref:'users'
},
Date: {
type: Date,
default: Date.now
},
Private: {type: Boolean, default: 'false'}
});
由于您有 default
任何新记录以及添加 private
之前保存的旧模型的任何新 实例 都会有它场.
如果您确实需要更多 dynamic
方法,通常的建议是使用 Mixed Type 以及随之而来的所有优点和缺点。
我最近开始为我的高级项目开发一个应用程序,它需要我使用某种类型的数据库。为此,我决定使用 Mongoose,因为它是 noSQL 并且更容易上手。
所以,快进,我 运行 遇到了一个问题,我无法弄清楚如何编辑现有架构并向其中添加新键。
例如,我有一个代表 post(想想 Tweets 或 Facebook posts)的架构,其中包含:
- 包含 post 正文的字符串
- 创建 post 的用户 ID
- 创建 post 的日期
我的代码是:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
// Create Schema
const PostsSchema = new Schema({
Value: {
type: String,
required: true
},
User: {
type: Schema.Types.ObjectId,
ref:'users'
},
Date: {
type: Date,
default: Date.now
}
});
// Create collection and add schema
mongoose.model('posts', PostsSchema, 'posts');
我现在想要的是以某种方式访问该架构并使用类似于
的方式向其添加新密钥PostsSchema.add({Private: { default: false}});
这意味着,现在数据库中的架构将类似于:
{
"_id": {
"$oid": "1831g98af21n9s5u7s9ccchj5"
},
"Value": "Beautiful day outside, can't wait to go jogging!",
"User": {
"$oid": "9a79ab143lbk9lk55wq327oi3226m"
},
"Date": {
"$date": "2018-10-29T01:28:44.408Z"
},
"Private": "false"
"__v": 0
}
所以回到我的问题,有什么办法可以做到这一点?或者,如果您有 link 此类方法的文档,我将不胜感激。非常感谢!
只需使用 default
:
const PostsSchema = new Schema({
Value: {
type: String,
required: true
},
User: {
type: Schema.Types.ObjectId,
ref:'users'
},
Date: {
type: Date,
default: Date.now
},
Private: {type: Boolean, default: 'false'}
});
由于您有 default
任何新记录以及添加 private
之前保存的旧模型的任何新 实例 都会有它场.
如果您确实需要更多 dynamic
方法,通常的建议是使用 Mixed Type 以及随之而来的所有优点和缺点。