0
const mongoose = require('mongoose');

const orgSchema = new mongoose.Schema({
org_name : {
    type : String,
    required : true
},
admin : {
    type : String,
    required : true
},
branches : [{
    branch_name : {
        type : String,
        required :true
    },
    branch_admin : {
        type : String,
        required : true
    },
    branch_locations : [{
        _id : false,
        sub_branch_name : {
            type : String
        },
        sub_branch_admin : {
            type : String
        }
    }]
}],
plan : {
    type : mongoose.Schema.Types.ObjectId,
    ref : 'plan',
    required : true
},
status : {
    type : String,
    enum : ['ACTIVE', 'EXPIRED']
}
});

orgSchema.createIndex = ({
 org_name : 1
},{
unique : true
});

module.exports = mongoose.model('organizations', orgSchema);

//Above is schema

    {
"_id" : ObjectId("5bf91a1edc7ed22ca90d4624"),
"org_name" : "xxxxxxxxxxxxxxx",
"admin" : "sssssss",
"branches" : [ 
    {
        "_id" : ObjectId("5bf91a1edc7ed22ca90d4625"),
        "branch_name" : "ssssss",
        "branch_admin" : "ddd",
        "branch_locations" : [ 
            {}//automatically creates empty doc when no fields
        ]
    }
],
"plan" : ObjectId("5bf91a1edc7ed22ca90d4623"),
"status" : "ACTIVE",
"__v" : 0

} when i try to insert a document with empty fields in the sub document array, it returns with {} in array of sub document. How to get rid from the new empty document in sub document. I should get an empty array when there is no field in the sub document to save...

RAJENDIRAN
  • 27
  • 7
  • `_id : required : false,` this is not valid. You cannot expect people to debug your code when you don't actually show your real code. Also you can't just say "when I insert", but you need to show an example of what you are doing in a way others can reproduce it as well. See [How to create a Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve) – Neil Lunn Nov 24 '18 at 09:58
  • sorry, i edited it while posting... – RAJENDIRAN Nov 24 '18 at 10:04
  • If you mean you're "hiding something" then what you are hiding is very likely the actual problem. Is that your real code their right now? It's not hard to copy and paste your code in here, and if you change anything then nobody can really answer you. Were you possibly attempting to suppress the `_id` field in the array? Because if that's what you were going for, then you did it wrong and this **IS** what is causing the "empty objects". – Neil Lunn Nov 24 '18 at 10:07
  • 1
    Possible Duplicate of : [Stop Mongoose from creating _id property for sub-document array items](https://stackoverflow.com/questions/17254008/stop-mongoose-from-creating-id-property-for-sub-document-array-items) where you have done `Schema({ _id: false })` instead of `Schema({ ... },{ _id: false })` effectively. Objects inside an array within a schema are implied to be a schema itself. – Neil Lunn Nov 24 '18 at 10:14

0 Answers0