Octtavius Octtavius - 1 month ago 7
Node.js Question

Why duplicates are save even if I use compound index? Mongo(Mongoose)

I am trying to save click coordinates on database but if x and y are the same I don't want to save them. Even if I use compound index and do everything by book, it still saves everything. There is similar question on stackoverflow but it doesn't work for my code.

Model, Schema:

var mongoose = require('mongoose');
var uniqueValidator = require('mongoose-unique-validator');
require('mongoose-double')(mongoose);
var Schema = mongoose.Schema;
var integerValidator = require('mongoose-integer');
var SchemaTypes = mongoose.Schema.Types;

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

clickPoint.index({x: 1, y: 1}, {unique: true});

clickPoint.plugin(integerValidator);
clickPoint.plugin(uniqueValidator);

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


Model Controller:

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

exports.addPoint = function (click) {
ClickPoint.findOne(function (err, data) {
if(!err) {
if(data) {
data.clicks.push({
x: click.x,
y: click.y,
value: click.value
});
data.save();
}
else {
var entry = new ClickPoint({
x: click.x,
y: click.y,
value: click.value
});

entry.save();
}
}
})
};


Could it be that all the records are stored in an array and as far as I know, index allows to store duplicates in array? If that is the problem than how would I keep objects unique in an array.

Answer

You index x & y, while the fields are click.x & click.y. If you're trying to add unique values to an array, why not use addToSet?