Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Web Technology by (50.2k points)

I want the project field of my document is unique across the whole collection but I am unable to implement that:

Refer to my code for 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;

Here is my code for 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();

I have run the app as:

node test.js

But it still generates replicas of the project field.

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") }

I also tried to delete the db.tasks.drop() collection and then restart mongo sudo. But it continues to generate duplicates!

Kindly help me... Thanks in advance.

1 Answer

0 votes
by (108k points)

I think you are passing the unique parameter inside your index that is why it is not generating your unique field. Try this:

var Tasks = new Schema({

    project: { 

        type: String, 

        unique: true,

        index: true

    },

    description: String

});

Below is a general way of making any field unique in MongoDB:

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

Browse Categories

...