Stop mongoose from creating _id property for sub-document array items

Stop mongoose from creating _id property for sub-document array items

Asked on January 2, 2019 in MongoDB.
Add Comment


  • 3 Answer(s)

    This is very simple, You can do this:

    var mongoose = require("mongoose");
    var subSchema = mongoose.Schema({
        //your subschema content
    },{ _id : false });
    var schema = mongoose.Schema({
        // schema content
    subSchemaCollection : [subSchema]
    });
    var model = mongoose.model('tablename', schema);
    
    Answered on January 2, 2019.
    Add Comment

    We can make sub-document without schema and avoid_id. then add _id:false to your subdocument declaration.

    var schema = new mongoose.Schema({
       field1:{type:String},
       subdocArray:[{
            _id:false,
            field :{type:String}
       }]
    });
    

    It will create an _id field in your subdoc. tested in Mongoose 3.8.1

    Answered on January 2, 2019.
    Add Comment

    further, if we using an object literal structure for specifying a sub-schema, you may also just add _id: false to supress it.

    {
       sub: {
          property1: String,
          property2: String,
          _id: false
       }
    }
    
    Answered on January 2, 2019.
    Add Comment


  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.