Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

set default values to mongoose arrays in node js

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

like image 547
Tal Levi Avatar asked Jan 09 '23 11:01

Tal Levi


1 Answers

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.

like image 144
Neil Lunn Avatar answered Jan 17 '23 14:01

Neil Lunn