Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to save array of objects in mongoose

I have this data from angular

 {
     "name": "Test name",
     "conditions": [
        {
         "id": "56a53ba04ce46bf01ae2bda7",
         "name": "First condition"             
        },
        {
         "id": "56a53bae4ce46bf01ae2bda8",
         "name": "Second condition"
        }
     ],
     "colors": [
        {
         "id": "56a545694f2e7a20064f228e",
         "name": "First color"
        },
        {
         "id": "56a5456f4f2e7a20064f228f",
         "name": "Second color"
        }
     ]
}

and I want to save this in ProductSchema in mongoDb but I don't know how to create schema for this

var ProductSchema = new Schema({
    name: String,
    conditions:  [Array],
    colors: [Array]
});

and how to save it to model in server controller

 var product = new Products({
    name: req.body.name,
    conditions: req.body.conditions,
    colors: req.body.colors
});

when I use this Schema and this controller I get empty record in collection except name and ObjectId. How to create right Schema and controller?

like image 734
Slip Avatar asked Jan 26 '16 21:01

Slip


2 Answers

Of course, the above answer works, consider this as an alternative.

var defaultArray = ["A","B","C"];
var schemaDef = mongoose.Schema(       
  permission: { type: Array, default: defaultArray },
);
like image 196
Nishant Shah Avatar answered Oct 24 '22 05:10

Nishant Shah


You need to create a mongoose model after you create your schema, and then you can save it. Try something like this:

var ProductSchema = new Schema({
name: String,
conditions:  [{}],
colors: [{}]
          });

var Product = mongoose.model('Product', productSchema);

var product = new Product({
    name: req.body.name,
    conditions: req.body.conditions,
    colors: req.body.colors
});

product.save( function(error, document){ //callback stuff here } );
like image 36
Brian Glaz Avatar answered Oct 24 '22 05:10

Brian Glaz