Octtavius Octtavius - 1 month ago 3
Node.js Question

How to save data to an array in Mongoose?

I would like to store every click event to an array in Mongoose and if there is no any array then it will create one for me.
At the moment it simply saves as object i.e. {x: 954, y: 256}, {x: 254, y: 156}
What I need is something like this [{x: 954, y: 256}, {x: 254, y: 156}]

Here is my code:

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


and here is the Controller that saves the data

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

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

entry.save();
};


Then I call this addPoint function from app.js

var clickPoint = require('./controllers/clickPoint.controller');

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


If you have any suggestions feel free offer them.

Answer

Update the Schema as follows -

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

Update the save functions

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

Suggestion - Store the Clicks based on user session or use some identifier to distinguish the client