Friday, 12 May 2017

Mongoose Default not working in nested schema

I have been working in Mongoose for a while and the default has always worked until now. Here is my schema:

var mongoose = require('mongoose');
var shortid = require('shortid');
var Schema = mongoose.Schema;

var ItemSchema = new Schema({
    id: {type: String, default: shortid.generate},
    icon: {
        local_name: String,
        url: String,
        tint_color: String
    },
    description: {en_US: String},
    subtitle: {en_US: String},
    title: {en_US: String},
    type: String,
    remember_value: Boolean,
    required: Boolean,
    items: [{type: Schema.Types.Object, ref: 'ItemSchema'}]
});

what I want to do is for every item that is a subitem of something I need an id to be generated. I have no idea if we will have 1 nested, 3 nested or 15 nested items. So what might come in is similar to this:

{
    "items": [{
            "title": "-HIVJnL-aweRRf100IAe",
            "type": "-HIVJnL-aweRRf200IVj"
        },
        {
            "title": "-HIVJnL-aweSSe444ISa",
            "type": "5001"
        },
        {
            "title": "-HIVJnL-aweSSe444IVa",
            "items": [{
                "title": "-HIVJnL-aweSS777IDa",
                "type": "hello",
                "items": [{
                    "title": "-HIVJnL-aweSS777IFa",
                    "type": "hello"
                }]
            }]
        }
    ]
}

What I need is that an ID field will be added with the default shorted generated when it is stored in the database. It does not see to work when I use the type: Schema.Types.Object



via Justin Yanta

No comments:

Post a Comment