最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - set default values to mongoose arrays in node js - Stack Overflow

programmeradmin0浏览0评论

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

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

Share Improve this question edited Jun 28, 2017 at 11:40 Neil Lunn 151k36 gold badges355 silver badges325 bronze badges asked Nov 11, 2014 at 9:22 Tal LeviTal Levi 3316 silver badges19 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 9

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 plex default through, you probably want to do this in a "pre save" hook instead. As a more plete 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.

发布评论

评论列表(0)

  1. 暂无评论