【问题标题】:Mongoose duplicates with the schema key unique具有唯一模式键的 Mongoose 重复项
【发布时间】:2012-02-19 21:41:45
【问题描述】:

我想让关键项目在该集合中独一无二,但我无法正常工作,我在这里发现了类似的问题。

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,再次运行程序还是同样的问题,它如何允许索引上的重复数据?

【问题讨论】:

    标签: node.js mongoose


    【解决方案1】:

    您传递的 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 中。

    【讨论】:

    猜你喜欢
    • 2021-09-09
    • 2017-02-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-03
    相关资源
    最近更新 更多