danielkr danielkr - 3 months ago 27
Javascript Question

MEAN-Stack save an array in MongoDB with mongoose

I am new to web development and I just ran into a problem I can't solve. I started with the MEAN-Stack so far and I encountered the following problem.

I have an array structure for a slider in my angular js Controller. From this array structure, I am trying to save a few values into my database.

Angular JS Controller snippet

$scope.alerts = [
{ id: 1,
title: 'CustomerCount',
value: 1,
weight: 30,
options: {
showTicks: true,
hidePointerLabels: true,
hideLimitLabels: true,
stepsArray: [
{ value: 1, legend: '<10' },
{ value: 2, legend: '<50' },
{ value: 3, legend: '<250' },
{ value: 4, legend: '<500' },
{ value: 5, legend: '>500' }

]
}
},
{ id: 2,
title: 'CustomerSatisfaction',
value: 3,
weight: 40,
options: {
showTicks: true,
hidePointerLabels: true,
hideLimitLabels: true,
stepsArray: [
{ value: 1, legend: '<10' },
{ value: 2, legend: '<50' },
{ value: 3, legend: '<250' },
{ value: 4, legend: '<500' },
{ value: 5, legend: '>500' }

]
}
}
];


From the above snippet, I'd like to save the title, the value and the weight of each alert in alerts

For this purpose, I have in the same angular js controller the following snippet

// Create new Article object
var article = new Articles({
title: this.title,
alert: this.alert,
});


As far as I understand does this snippet create a new article entry in my database using the following schema defined in the server.model.js file

var mongoose = require('mongoose'),
Schema = mongoose.Schema;

/**
* Article Schema
*/
var ArticleSchema = new Schema({
created: {
type: Date,
default: Date.now
},
user: {
type: Schema.ObjectId,
ref: 'User'
},
alert: [{ value: Number, weight: Number, title: String }]
});


mongoose.model('Article', ArticleSchema);


But my Problem now is that this only saves an empty array in MongoDB.

The solution presented below lead to the solution. It has to be noted that

var mongoose = require('mongoose'),
Schema = mongoose.Schema;

/**
* Article Schema
*/
var ArticleSchema = new Schema({
created: {
type: Date,
default: Date.now
},
user: {
type: Schema.ObjectId,
ref: 'User'
},
alerts: []
});

// Create new Article object
var article = new Articles({
title: this.title,
alerts: this.alerts,
});


Delivered the wanted solution!

Answer

Change your schema to this and it should work:

var mongoose = require('mongoose'),
  Schema = mongoose.Schema;

/**
 * Article Schema
 */
var ArticleSchema = new Schema({
  created: {
    type: Date,
    default: Date.now
  },
  user: {
    type: Schema.ObjectId,
    ref: 'User'
  },
  alert: []
});


mongoose.model('Article', ArticleSchema);

I managed to save arrays in mongodb by just specifying [] in the schema and then you can save multiple objects in the array.

Comments