Octtavius Octtavius - 1 year ago 118
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');
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});


//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) {
x: click.x,
y: click.y,
value: click.value
else {
var entry = new ClickPoint({
x: click.x,
y: click.y,
value: click.value


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 Source

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?

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download