如何将数据保存到Mongoose中的数组?

时间:2016-10-19 14:44:54

标签: node.js mongodb mongoose mongoose-schema

我想将每个click事件存储到Mongoose中的数组中,如果没有任何数组,那么它将为我创建一个数组。 目前它只是保存为对象,即{x:954,y:256},{x:254,y:156} 我需要的是这样的[{x:954,y:256},{x:254,y:156}]

这是我的代码:

clickModel Schema

enter code var mongoose = require('mongoose');
require('mongoose-double')(mongoose);
var Schema = mongoose.Schema;
var integerValidator = require('mongoose-integer');
var SchemaTypes = mongoose.Schema.Types;

var clickPoint = new Schema({
    x: {
        type: SchemaTypes.Double
    },
    y: {
        type: SchemaTypes.Double
    },
    value: {
        type: Number,
        integer: true
    }
});

clickPoint.plugin(integerValidator);

//export model...
module.exports = mongoose.model("ClickPoint", clickPoint);

这是保存数据的Controller

var ClickPoint = require('../Models/point');

exports.addPoint = function (click) {
    var entry = new ClickPoint({
        x: click.x,
        y: click.y,
        value: click.value
    });

    entry.save();
};

然后我从app.js

调用此addPoint函数
var clickPoint = require('./controllers/clickPoint.controller');

app.post('/clickPoint', function (req, res) {
    clickPoint.addPoint(req.body);
});

如果您有任何建议,请随时提供。

1 个答案:

答案 0 :(得分:2)

按如下方式更新架构 -

var clickPoint = new Schema({
  clicks: [
    x: {
      type: SchemaTypes.Double
    },
    y: {
      type: SchemaTypes.Double
    },
    value: {
      type: Number,
      integer: true
    }
  ]
});

更新保存功能

ClickPoint.findOne(function(err, data) {
  if (!err) {
    if (data) {
      data.clicks.push({
        x: click.x,
        y: click.y,
        value: click.value
      })
      data.save();

    } else {
      new ClickPoint({
        clicks: [{
          x: click.x,
          y: click.y,
          value: click.value
        }]
      });

      entry.save();
    }
  }
});

建议 - 根据用户会话存储点击或使用一些标识符来区分客户端