在Node.js中,为Mongoose数组设置默认值

4

在我的模型定义中,我有:

appFeatures: [{
        name: String,
        param : [{
            name : String,
            value : String
        }]
    }]

我希望为appFeatures设置默认值,例如: name: 'feature', param: [{name:'param1',value:'1'},{name:'param2',value:'2'}]

我尝试通过以下方式实现:

appFeatures : { type : Array , "default" : ... }

但是它没有生效,有什么想法吗?
谢谢。
1个回答

9

Mongoose允许您“分离”模式定义。这样可以实现通用“重用”和代码的清晰性。因此,更好的方法是:

// general imports
var mongoose = require('mongoose'),
    Schema = mongoose.Schema;

// schema for params
var paramSchema = new Schema({
    "name": { "type": String, "default": "something" },
    "value": { "type": String, "default": "something" }
});

// schema for features
var featureSchema = new Schema({
    "name": { "type": String, "default": "something" }
    "params": [paramSchema]
});

var appSchema = new Schema({
    "appFeatures": [featureSchema]
});

// Export something - or whatever you like
module.export.App = mongoose.model( "App", appSchema );

因此,如果您愿意将“模式”定义作为各个模块的一部分,并使用“require”系统根据需要导入,那么它就是“干净的”和“可重用的”。如果不想将所有内容都放进“模块”,还可以从“模型”对象中“内省”模式定义。最重要的是,它允许您明确地指定默认值。
对于更复杂的默认值,则可能需要在“pre save”钩子中执行此操作。以下是一个更完整的示例:
var async = require('async'),
    mongoose = require('mongoose'),
    Schema = mongoose.Schema;

var paramSchema = new Schema({
  "name": { "type": String, "default": "something" },
  "value": { "type": String, "default": "something" }
});

var featureSchema = new Schema({
  "name": { "type": String, "default": "something" },
  "params": [paramSchema]
});

var appSchema = new Schema({
  "appFeatures": [featureSchema]
});

appSchema.pre("save",function(next) {
  if ( !this.appFeatures || this.appFeatures.length == 0 ) {
    this.appFeatures = [];
    this.appFeatures.push({
      "name": "something",
      "params": []
    })
  }

  this.appFeatures.forEach(function(feature) {
    if ( !feature.params || feature.params.length == 0 ) {
      feature.params = [];
      feature.params.push(
       {  "name": "a", "value": "A" },
       {  "name": "b", "value": "B" }
      );
    }
  });
  next();
});


var App = mongoose.model( 'App', appSchema );

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


async.series(
  [
    function(callback) {
      App.remove({},function(err,res) {
        if (err) throw err;
        callback(err,res);
      });
    },
    function(callback) {
      var app = new App();
      app.save(function(err,doc) {
        if (err) throw err;
        console.log(
          JSON.stringify( doc, undefined, 4 )
        );
        callback()
      });
    },
    function(callback) {
      App.find({},function(err,docs) {
        if (err) throw err;
        console.log(
          JSON.stringify( docs, undefined, 4 )
        );
        callback();
      });
    }
  ],
  function(err) {
    if (err) throw err;
    console.log("done");
    mongoose.disconnect();
  }
);

您可以清理该数组并检查模式路径以获取其他级别的默认值。但基本上您要说的是如果未定义该内部数组,则将填充编码的默认值。


谢谢,您能解释一下我如何添加两个featureSchema吗?就像我的例子一样?再次感谢! - Tal Levi
@TalLevi 当然。在那里添加了一个更完整的示例,用于添加两个内部项。 - Neil Lunn

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接