Ajay
Ajay

Reputation: 1281

MongoDB - unwanted generation of ObjectId for sub array item

I am getting unwanted ObjectId creation automatically while creating a record in MongoDB using Mongoose in Node.js. The record generated in MongoDB is perfect except ObjectId ("540dc9c35ae5b576d96f9d54") for array item.

How could stop to generate the ObjectId for sub array item?

Also what is "__v" : 0 appears in mongoDB row (C) ?

Below are details,

A. Mongoose Model Schema:

var Result = new Schema ({
name : String,
class : String,   
result : [{
    subject : String,    
    marks : Number
}]
});

B. execution script:

Model.Result.create({
        name : “name1”,
        class : “6th”,
        result : [{
            subject : “math”,
            marks : 75
        }]
}, function(err){});

C. row created in mongoDB:

{ 
"name" : "name1", 
"class" : 6, 
"_id" : ObjectId("540dc9c35ae5b576d96f9d53"), 
"result" : [
            { 
              "subject" : "math",   
              "_id" : ObjectId("540dc9c35ae5b576d96f9d54"),   
              "marks" : 75
           }], 
"__v" : 0 
}

Upvotes: 0

Views: 301

Answers (1)

Timothy Strimple
Timothy Strimple

Reputation: 23070

Just set the _id to false in the subdocument.

var Result = new Schema ({
name : String,
class : String,   
result : [{
    _id: false,
    subject : String,    
    marks : Number
}]
});

The __v a version key used by mongoose to track changes to array indexes. It ensures that if you're trying to update result[0], you actually update the row you want. Just in case someone does a $push ahead of your update in which case you would be updating the wrong sub document. You can read more about it here.

Upvotes: 2

Related Questions