MEAN-Stack save an array in MongoDB with mongoose

不想你离开。 提交于 2019-12-23 05:59:17

问题


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!


回答1:


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.




回答2:


You need to call the save method on the Article schema. Only then the article is saved

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

article.save(function(err, doc){
  if(!err){
    // Article saved! "doc" is the reference
  }else{
    console.error('Error on saving the article');
  }
});

Here is the mongoose save documentation for reference




回答3:


If You are using MEAN then Saving data comes on server which is handle on Express, Mongodb(Mongoose) and Nodejs.

I am assuming that you are using Meanjs of yo

First you need to make a route where which is called by your angular $http ajax Route: article.server.route.js

 // Articles collection routes
  app.route('/api/articles')
    .post(articles.create);

Controller: article.server.controller.js

exports.create = function (req, res) {
  var article = new Article(req.body);
  article.user = req.user;

  article.save(function (err) {
    if (err) {
      return res.status(400).send({
        message: err
      });
    } else {
      res.json(article);
    }
  });
};


来源:https://stackoverflow.com/questions/38783378/mean-stack-save-an-array-in-mongodb-with-mongoose

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!