mongoose 如何在架构中强制一组属性值的唯一性?

osh3o9ms  于 2022-11-13  发布在  Go
关注(0)|答案(1)|浏览(203)

我正在用MongooseJS做一个朋友请求,我在MongoDB中存储了一个tofrom密钥,它们是发送者和接收者的用户ID。我想防止同一个发送者向同一个接收者发出重复的请求。
下面是我的架构:

import { model, Schema, Document } from 'mongoose';
import { FriendRequestInterface } from '@interfaces/friendrequest.interface';
import { FriendRequestStatus } from '@/enums/enumFriendRequest';

const friendRequestSchema: Schema = new Schema({
  to: {
    type: String,
    required: true,
    // unique: true,
  },
  from: {
    type: String,
    required: true,
    // unique: true,
  },
  message: {
    type: String,
    required: false,
  },
  status: {
    type: String,
    enum: FriendRequestStatus,
    required: true,
  },
});

friendRequestSchema.index({ to: 1, from: 1 }, { unique: true });
const friendRequestModel = model<FriendRequestInterface & Document>('FriendRequest', friendRequestSchema);
export default friendRequestModel;

我发布的内容:

{
    "to": "636acf77378903f78b388339",
    "from": "636acf83378903f78b38833f",
    "message": "Hello, I want to be your friend.",
    "status": "pending"
}

Postman 错误:

{
    "message": "E11000 duplicate key error collection: db_dev.friendrequests index: from_1 dup key: { from: \"636acf83378903f78b38833f\" }"
}
xe55xuns

xe55xuns1#

显然,我的问题是我在MongoDB中的集合中仍然设置了索引,这会造成干扰。我清除了我在混乱中创建的所有索引,并以如下方式添加了索引(复合):
friendRequestSchema.index({ to: 1, from: 1 }, { unique: true, sparse: true });

相关问题