71

次のようなスキーマがあるとします。

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

同じ firstName と lastName を持つドキュメントが 1 つだけであることを確認したいと思います。

どうすればこれを達成できますか?

4

6 に答える 6

124

indexスキーマの呼び出しを使用して、一意の複合インデックスを定義できます。

person.index({ firstName: 1, lastName: 1}, { unique: true });
于 2013-04-17T18:21:04.017 に答える
1
const personSchema = new Schema({ firstName:  String, lastName: String });
const person = mongoose.model('recipients', personSchema);
person.createIndexes();

コレクション内のすべての重複を取り除くか、より速く簡単な方法で行う必要がある場合があります。

コードを編集し、コレクションをドロップしてから、Mongo を再起動します。

于 2019-05-08T07:58:21.093 に答える
0

私はこれを試していませんが、一意のインデックスを使用するとうまくいくはずです。

db.person.ensureIndex( { "firstname": 1, "lastname": 1 }, { unique: true } )
于 2013-04-17T13:51:23.463 に答える
-2

このようにスキーマを定義できます。

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 }
    });
于 2019-12-15T10:31:36.480 に答える