I have a JSON which I want to store in collection using Mongoose. Function that I am using to insert the document into collection is :
UserSchema.statics.SaveDocument=function(docs,callback){
docs=JSON.parse(docs);
this.create(docs,function(err,data){
if(err) callback(err);
else callback(data);
});
};
Schema for the collection is :
var UserSchema = new Schema({
A : String,
B : String,
C : [
{
D : Schema.Types.ObjectId,
E : String,
}
]
});
The JSON format which I am trying to store is like :
{
"A" : "something",
"B" : "something",
"C" : [
{
"D" : "something",
"E" : "Something",
}
],
}
and the document being stored into collection looks like :
{
"_id" : ObjectId("55XXXXX"),
"A" : "something",
"B" : "something",
"C" : [
{
"D" : "something",
"E" : "Something",
"_id" : ObjectId("56XXXXX"),
}
],
"__v" : 0
}
Now, what I want is to store the ObjectId being generated by my funtion and not to to store that additional ObjectID that mongoose is inserting in the array of element C.
I know that by using { id: false } in function I can disable autogenerated ID but I can't use that for that unnecessary ID inserted by mongoose in C because that eliminates both ObjectID .
So can someone help me how I can do this ?
Another thing is I don't have any Idea where from "__V": 0 is coming into the collection ?
For __V part: You can disable it by appending { versionKey: false } see: http://mongoosejs.com/docs/guide.html#versionKey
To remove that _id in C you can define a subschema like
var C = mongoose.Schema({
//C schema content
},{ _id : false });
and change your original schema to something like :
var UserSchema = new Schema({
A : String,
B : String,
C : [subSchema] ....
...)};
Then try inserting the new doc.
It can also be done by adding _id : false in element C of Schema:
var UserSchema = new Schema({
C : [
{
D : Schema.Types.ObjectId,
E : String,
_id : false
}
]
});
Sub schema helps you when you have more than one schema using same sub structure, but here I only have one schema so using sub schema does not sense good.