为什么我的架构没有在 mongoose 数组中添加默认值? [英] Why doesn't my schema to add default values in mongoose arrays?

查看:59
本文介绍了为什么我的架构没有在 mongoose 数组中添加默认值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样的架构:

var CustomUserSchema = new Schema({角色: [],权限:[],});

permissions 字段存储一个字符串数组,如下所示:

[删除"、显示"、创建"]

role 字段存储一个对象数组,如下所示:

<预><代码>[{姓名:管理员",优先级:10,权限:[删除"、显示"、更新"]},{姓名:用户",优先级:5,权限:[删除",显示"]}]

现在,我的要求是能够将显示"存储为架构中 permissions 字段的默认值,并将用户"存储为角色字段内名称的默认值,优先级 0role 字段内的 priorityrole 字段内的 permissions 'Show'.

尝试自己,我想出了这个:

var CustomUserSchema = new Schema({角色: [{名称:{类型:字符串,默认值:'用户'},优先级:{ 类型:数字,默认值:0 } ,权限:[{type:String, default:'Show'}]}],权限:[{type:String, default:'Show'}]});

但它根本不为字段分配默认值,而是为字段提供大小为 0 的数组.

上面的架构似乎有什么问题?如何将这些存储为默认值?

解决方案

默认值确实不适用于数组,除非它是数组中的文档,并且您想在添加时为该文档设置默认属性到数组.

因此数组总是被初始化为空",除非你故意在其中放入一些东西.为了做你想要实现的目标,然后添加一个 pre save hook 来检查空数组,然后以其他方式放置那里的默认值:

var async = require('async'),猫鼬 = 要求('猫鼬'),架构 = 猫鼬.架构;mongoose.connect('mongodb://localhost/authtest');var userSchema = new Schema({权限:[{类型":字符串,"enum": ["删除","显示","创建","更新"],}]});userSchema.pre("save",function(next) {如果(this.permissions.length == 0)this.permissions.push("显示");下一个();});var User = mongoose.model('User', userSchema);var user = new User();用户.保存(功能(错误,用户){如果(错误)抛出错误;控制台日志(用户);});

创建空值:

{ __v: 0,_id:55c2e3142ac7b30d062f9c38,权限:['显示']}

当然,如果您初始化数据或操作以在数组中创建条目:

var user = new User({"permissions":["Create"]});

然后你得到你添加的数组:

{ __v: 0,_id:55c2e409ec7c812b06fb511d,权限:['创建']}

如果您想始终"在权限中显示显示",那么对钩子进行类似的更改可以为您强制执行:

userSchema.pre("save",function(next) {if (this.permissions.indexOf("Show") == -1)this.permissions.push("显示");下一个();});

结果:

var user = new User({"permissions":["Create"]});{ __v: 0,_id:55c2e5052219b44e0648dfea,权限:['创建','显示']}

这些是您可以控制数组条目默认值的方法,而无需使用模型在代码中显式分配它们.

I have a schema like this:

var CustomUserSchema = new Schema({
    role: [],
    permissions: [],
});

permissions field store an array of strings that looks like this:

["Delete", "Show","Create"]

whereas

role field stores an array of objects that looks like this:

[
    {
        name:"admin",
        priority:10,
        permissions: ["Delete", "Show" , "update"]
    },
    {
        name:"user",
        priority:5,
        permissions: ["Delete", "Show"]
    }
]

Now, my requirement is to be able to store "Show" as default value for permissions field in the schema and to store 'user' as default value for name inside of role field , priority 0 for priority inside of role field and 'Show' for permissions inside of role field.

Trying myself, I came up with this:

var CustomUserSchema = new Schema({
    role: [{
        name: {type: String, default: 'user'},
        priority:{ type: Number, default: 0 } ,
        permissions: [{type:String, default:'Show'}]
    }],
    permissions: [{type:String, default:'Show'}]
});

But it does not assign the default values to the fields at all and gives an array of size 0 to the fields .

What seems wrong with above schema? How do I store these as default values?

解决方案

Default values really don't work with arrays, unless of course it is a document within the array and you want to set a default property for that document when added to the array.

Therefore an array is always initialized as "empty" unless of course you deliberately put something in it. In order to do what you want to achieve, then add a pre save hook that checks for an empty array and then otherwise places a default value in there:

var async = require('async'),
    mongoose = require('mongoose'),
    Schema = mongoose.Schema;

mongoose.connect('mongodb://localhost/authtest');

var userSchema = new Schema({
  permissions:[{
    "type": String,
    "enum": ["Delete","Show","Create","Update"],
  }]
});

userSchema.pre("save",function(next) {
  if (this.permissions.length == 0)
    this.permissions.push("Show");

  next();
});

var User = mongoose.model( 'User', userSchema );

var user = new User();

user.save(function(err,user) {
  if (err) throw err;
  console.log(user);
});

Which creates the value where empty:

{ __v: 0,
  _id: 55c2e3142ac7b30d062f9c38,
  permissions: [ 'Show' ] }

If of course you initialize your data or manipulate to create an entry in the array:

var user = new User({"permissions":["Create"]});

Then you get the array you added:

{ __v: 0,
  _id: 55c2e409ec7c812b06fb511d,
  permissions: [ 'Create' ] }

And if you wanted to "always" have "Show" present in permissions, then a similar change to the hook could enforce that for you:

userSchema.pre("save",function(next) {
  if (this.permissions.indexOf("Show") == -1)
    this.permissions.push("Show");

  next();
});

Which results in:

var user = new User({"permissions":["Create"]});

{ __v: 0,
  _id: 55c2e5052219b44e0648dfea,
  permissions: [ 'Create', 'Show' ] }

Those are the ways you can control defaults on your array entries without needing to explicitly assign them in your code using the model.

这篇关于为什么我的架构没有在 mongoose 数组中添加默认值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆