Question

[Solved] 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

Solution #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.

Respondent: Neil Lunn
The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .

Most Popular

To Top
India and Pakistan’s steroid-soaked rhetoric over Kashmir will come back to haunt them both clenbuterol australia bossier man pleads guilty for leadership role in anabolic steriod distribution conspiracy