如何创建一个对象数组并使用mongoose将该数组保存在mongodb中

时间:2016-08-04 12:56:08

标签: javascript angularjs mongodb mongoose mean-stack

我是网络开发的新手,刚开始使用MEAN-Stack。我很高兴能得到任何帮助。

我简单地遇到了以下问题:

  • 我有一个像这样的$ scope数组

    $ scope.alerts = [{...},{...} {...}]

  • 从这个数组中,我想在每个对象中使用mongoose将两个值发布到MongoDB

现在问题更具体。

我有一个带有对象的数组,如下所示:

AngularJS Controller Snippet

$scope.alerts = [
    { id: 1,
      title: 'someTitle1',
      weighttitle: 'someWeightTitle1',
      value: 1,
      weight: 30,
      options: {
        showTicks: true,
        hidePointerLabels: true,
        hideLimitLabels: true,
        stepsArray: [
            { value: 1, legend: 'Very poor' },
            { value: 2, legend: 'Very poor' },
            { value: 3, legend: 'Fair' },
            { value: 4, legend: 'Very poor' },
            { value: 5, legend: 'Average' }

        ]
      }
    },
    { id: 2,
      title: 'someTitle2',
      weighttitle: 'someWeightTitle2',
      value: 1,
      weight: 60,
      options: {
        showTicks: true,
        hidePointerLabels: true,
        hideLimitLabels: true,
        stepsArray: [
            { value: 1, legend: 'Very poor' },
            { value: 2, legend: 'Very poor' },
            { value: 3, legend: 'Fair' },
            { value: 4, legend: 'Very poor' },
            { value: 5, legend: 'Average' }

        ]
      }
    }
];

我在Controller中有部分为mongoose创建对象

与上面代码相​​同的AngularJS控制器

var article = new Articles({
    title: this.title,
    someTitle1: {
      value: this.value,
      weight: this.weight,
    }
  });

title: this title按预期工作并创建数据库条目,但someTitle不会。

此时,允许在MongoDB中编写一些数组会很好。

此方案的架构如下所示:

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

/**
 * Article Schema
 */
var ArticleSchema = new Schema({
  created: {
    type: Date,
    default: Date.now
  },
  title: {
    type: String,
    default: '',
    trim: true,
    required: 'Title cannot be blank'
  },
  user: {
    type: Schema.ObjectId,
    ref: 'User'
  },
  someTitle1: {
    value: Number,
    weight: Number
  }


});

mongoose.model('Article', ArticleSchema);

我想知道是否不可能

0 个答案:

没有答案