Mongoose: how to define a combination of fields to be unique?

后端 未结 6 1849
半阙折子戏
半阙折子戏 2020-11-27 04:35

If I had a schema like this:

var person = new Schema({
  firstName:  String,
  lastName: String,
});

相关标签:
6条回答
  • 2020-11-27 04:58

    You can define a unique compound index using an index call on your schema:

    person.index({ firstName: 1, lastName: 1}, { unique: true });
    
    0 讨论(0)
  • 2020-11-27 04:58
    const personSchema = new Schema({ firstName:  String, lastName: String });
    const person = mongoose.model('recipients', personSchema);
    person.createIndexes();
    

    You might need to get rid of all duplicates in the collection or do it the faster and easy way :

    Edit your Code, Drop the Collection and then restart Mongo.

    0 讨论(0)
  • 2020-11-27 04:58

    You can define Your Schema like this.

    const mongoose = require("mongoose");
    const Schema = mongoose.Schema;
    const bcrypt = require("bcryptjs");
    
        const userSchema = new Schema({
          firstName: {
            trim: true,
            type: String,
            required: [true, "firstName is required!"],
            validate(value) {
              if (value.length < 2) {
                throw new Error("firstName is invalid!");
              }
            }
          },
          lastName: {
            trim: true,
            type: String,
            required: [true, "lastName is required!"],
            validate(value) {
              if (value.length < 2) {
                throw new Error("lastName is invalid!");
              }
            }
          },
          username: {
            unique: [true, "Username already available"],
            type: String,
            required: [true, "Username is required"],
            validate(value) {
              if (value.length < 10) {
                throw new Error("Username is invalid!");
              }
            }
          },
          mobile: {
            unique: [true, "Mobile Number alraedy available"],
            type: String,
            required: [true, "Mobile Number is required"],
            validate(value) {
              if (value.length !== 10) {
                throw new Error("Mobile Number is invalid!");
              }
            }
          },
          password: {
            type: String,
            required: [true, "Password is required"],
            validate(value) {
              if (value.length < 8) {
                throw new Error("Password is invalid!");
              }
            }
          },
          gender: {
            type: String
          },
          dob: {
            type: Date,
            default: Date.now()
          },
          address: {
            street: {
              type: String
            },
            city: {
              trim: true,
              type: String
            },
            pin: {
              trim: true,
              type: Number,
              validate(value) {
                if (!(value >= 100000 && value <= 999999)) {
                  throw new Error("Pin is invalid!");
                }
              }
            }
          }
          date: { type: Date, default: Date.now }
        });
    
    0 讨论(0)
  • 2020-11-27 05:01

    I haven't tried this, but using a unique index should do the trick.

    db.person.ensureIndex( { "firstname": 1, "lastname": 1 }, { unique: true } )
    
    0 讨论(0)
  • defining your schema like this

    
    var person = new Schema({
    firstName:  String,
    lastName: String,
    index: true,
    unique: true, 
    
    });
    
    

    or

    
    person.index({ firstName: 1, lastName: 1}, { unique: true });
    
    
    0 讨论(0)
  • 2020-11-27 05:06

    Fun little thing I only recently discovered through experimentation with Mongoose. I have the following schema for example:

    const ShapesSchema = new mongoose.Schema({
      name: { type: String, required: true },
      user: { type: mongoose.Schema.Types.ObjectId, ref: 'User' }
    })
    
    ShapesSchema.index({ name: 1, user: 1 }, { unique: true })
    
    mongoose.model('Shapes', ShapesSchema)
    

    The idea was to create a compound index that was unique on name and user together. This way a user could create as many shapes as they wanted as long as each of their shapes had a distinct name. And the inverse was supposed to be true as well - shapes could have the same name as long as they had different users. It didn't work out like that for me.

    What I noticed was that aside from the index on _id, three other index entries were created. One each for name, user, and name_user all set to be unique. I made a modification to the schema and included unique: false to each of the fields I was using for the compound index and suddenly it all worked as expected. What I ended up with was:

    const ShapesSchema = new mongoose.Schema({
      name: { type: String, required: true, unique: false },
      user: { type: mongoose.Schema.Types.ObjectId, ref: 'User', unique: false }
    })
    
    ShapesSchema.index({ name: 1, user: 1 }, { unique: true })
    
    mongoose.model('Shapes', ShapesSchema)
    

    Looking at the indexes that were created as a result I still see the three indexes - name, user, and name_user. But the difference is that the first two are not set to be unique where the last one, the compound, is. Now my use case of multiple distinct shapes per user, or identically named shapes with different users works like a champ.

    0 讨论(0)
提交回复
热议问题