set default values to mongoose arrays in node js

跟風遠走 提交于 2019-12-07 15:33:14

问题


In my model definition, I have:

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

I want to set default value to appFeatures, for example: name: 'feature', param: [{name:'param1',value:'1'},{name:'param2',value:'2'}]

I tried to do it by

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

But its not working, any ideas?

Thanks


回答1:


Mongoose allows you to "separate" schema definitions. Both for general "re-use" and clarity of code. So a better way to do this is:

// 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 );

So it's "clean", and "re-usable" if you are willing to make "Schema" definitions part of individual modules and use the "require" system to import as needed. You can even "introspect" schema definitions from "model" objects if you don't want to "module" everything.

Mostly though, it allows you to clearly specify "what you want" for defaults.

For a more complex default through, you probably want to do this in a "pre save" hook instead. As a more complete example:

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();
  }
);

You could clean that up and introspect the schema path to get default values at other levels. But you basically want to say if that inner array is not defined then you are going to fill in the default values as coded.



来源:https://stackoverflow.com/questions/26861417/set-default-values-to-mongoose-arrays-in-node-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!