即使我使用复合索引,为什么要重复保存?蒙哥(猫鼬)

时间:2016-10-20 14:29:23

标签: node.js mongodb mongoose mongoose-schema

我正在尝试保存数据库上的点击坐标,但如果x和y相同,我不想保存它们。即使我使用复合索引并按书完成所有操作,它仍然可以保存所有内容。 stackoverflow上有类似的问题,但它对我的代码不起作用。

模型,架构:

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

模型控制器:

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

可能是所有记录都存储在一个数组中,据我所知,index允许在数组中存储重复项吗?如果这是问题,那么我将如何在数组中保持对象的唯一性。

1 个答案:

答案 0 :(得分:1)

您索引x& y,而字段为clicks.x& clicks.y。如果您尝试向数组添加唯一值,为什么不使用addToSet