I´m trying to save an array on MongoDB using mongoose. Here is my model:
let itemFields = { "name": { "type": "String", "required": true, "unique": true } };
let modelFields = {
"name": { "type": "String", "required": true, "unique": true },
"description": { "type": "String" },
"options": { "type": "Array", "ref": "SelectOptionItem" },
"company_id": { "type": "ObjectId", "ref": "Company", "required": true },
"deleted": { "type": "Boolean", "required": true },
"createdAt": { "type": "Number" },
"updatedAt": { "type": "Number" }
};
const SelectOptionItem = new mongoose.Schema(itemFields);
const schema = new mongoose.Schema(modelFields);
Later I have the following code to save data:
schema.statics.create = async function(context, data) {
console.log("Saved data:");
console.log(data);
let so = new this(data);
so.save();
}
Where I get the following log:
Saved data:
{ name: 'aa',
description: 'aa',
options: [ { name: '1' }, { name: '2' } ],
company_id: '59b2cd9a072e4f28b839aaa0',
deleted: false,
createdAt: 1511569192524 }
Finally, this is what I´m getting in the mongo console:
> db.selectoptions.find({});
{ "_id" : ObjectId("5a18b7288c688033a4adcb0c"), "name" : "aa", "description" : "aa", "company_id" : ObjectId("59b2cd9a072e4f28b839aaa0"), "deleted" : false, "createdAt" : 1511569192524, "options" : [ [ { "name" : "1" } ], [ { "name" : "2" } ] ], "__v" : 0 }
Repair that options is being an array of array ([[]]). Later when retrieving that data I´m having problems as I´m expecting a single array.
I need to undestand why mongoose is saving an array of array at options field and how to solve that.