15

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?

1
  • it's not an array of objects, it's just an object Commented Apr 13, 2022 at 3:31

2 Answers 2

12

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 } );
Sign up to request clarification or add additional context in comments.

4 Comments

Yes i did but it seems to me it's wrong schema or error in ` conditions: req.body.conditions, colors: req.body.colors` . I get in my collection saved name and objectId only . No conditions or colors.
Edited my answer.. I think you need to change the schema types for conditions and colors.
When I try to save it saves at 0th index but I have 2 elements here: services: "[{"service": "A1", "price": "1000"}, {"service": "A2", "price": "100..."
i have a question, when I add a new object to the conditions array is the previous values will be overwritten or it will just be added to the last of the array ?
1

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 },
);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.