为什么即使我使用复合索引也保存了重复项? Mongo(Mongo)
Why duplicates are save even if I use compound index? Mongo(Mongoose)
我正在尝试将点击坐标保存在数据库中,但如果 x 和 y 相同,我不想保存它们。即使我使用复合索引并按书做所有事情,它仍然可以保存所有内容。 Whosebug 上有类似的问题,但它不适用于我的代码。
模型、架构:
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();
}
}
})
};
难道所有的记录都存储在一个数组中,据我所知,索引允许在数组中存储重复项?如果那是问题所在,我将如何使对象在数组中保持唯一。
您索引 x
& y
,而字段是 clicks.x
& clicks.y
。如果您尝试向数组添加唯一值,为什么不使用 addToSet
?
我正在尝试将点击坐标保存在数据库中,但如果 x 和 y 相同,我不想保存它们。即使我使用复合索引并按书做所有事情,它仍然可以保存所有内容。 Whosebug 上有类似的问题,但它不适用于我的代码。
模型、架构:
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();
}
}
})
};
难道所有的记录都存储在一个数组中,据我所知,索引允许在数组中存储重复项?如果那是问题所在,我将如何使对象在数组中保持唯一。
您索引 x
& y
,而字段是 clicks.x
& clicks.y
。如果您尝试向数组添加唯一值,为什么不使用 addToSet
?