Mongoose 重复且架构键唯一

2024-05-15

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

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

当我使用 Node 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 停止 mongodb 并启动 mongodb,再次运行程序,仍然存在同样的问题,它如何允许索引上的重复数据?


您传递的 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”参数做什么,它似乎不在猫鼬文档 http://mongoosejs.com/docs/schematypes.html.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Mongoose 重复且架构键唯一 的相关文章

随机推荐