我想让关键项目在该系列中独一无二,但是我无法使其正常工作,我在这里发现了类似的问题。
task.js
function make(Schema, mongoose) {
var Tasks = new Schema({
project: { type: String, index: { unique: true, dropDups: true }},
description: String
});
mongoose.model('Task', Tasks);
}
module.exports.make = make;
test.js
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/rss');
var Schema = mongoose.Schema
, ObjectId = Schema.ObjectId;
require('./task.js').make(Schema, mongoose);
var Task = mongoose.model('Task');
var newTask = new Task({
project: 'Starting new project'
, description: 'New project in node'
});
newTask.save(function(err) {
if (err) console.log('Error on saving');
});
mongoose.disconnect();
当我使用节点test.js运行应用程序时,仍会创建重复项。
MongoDB shell version: 2.0.2
connecting to: rss
> db.tasks.find()
> db.tasks.find()
{ "project" : "Starting new project", "description" : "New project in node", "_id" : ObjectId("4f21aaa3d48d4e1533000001") }
{ "project" : "Starting new project", "description" : "New project in node", "_id" : ObjectId("4f21aaa4d9a8921a33000001") }
{ "project" : "Starting new project", "description" : "New project in node", "_id" : ObjectId("4f21aaa57ebeea1f33000001") }
//编辑仍然是同样的问题,这是我试图做的 删除db.tasks.drop()集合 重新启动mongo sudo stop mongodb并启动mongodb,再次运行该程序仍然存在同样的问题,它如何允许索引上的重复数据?
答案 0 :(得分:29)
您传递的Schema对象可能无法正常工作,因为您将'unique'属性嵌套到'index'属性中,尝试这样的事情(它按预期工作):
User = mongoose.model('User', new Schema({
firstName: {
type:String,
required: true,
},
lastName: {
type:String,
required: true,
},
email: {
type:String,
required: true,
unique: true
},
address: String,
phone: {
type:String,
required: true,
},
password: {
type:String,
required: true,
set: Data.prototype.saltySha1 // some function called before saving the data
},
role: String
},{strict: true}));
或者更具体地说是你的例子:
var Tasks = new Schema({
project: {
type: String,
unique: true,
index: true
},
description: String
});
注意:我不知道你在尝试使用“dropDups”参数做什么,它似乎不在mongoose documentation中。