在Mongoose / MongoDB中创建多字段索引

sh7euo9m  于 2022-11-13  发布在  Go
关注(0)|答案(5)|浏览(208)

我试着寻找文档,但没有找到关于如何在Mongoosejs中创建多字段索引的文档。特别是我有两个字段需要索引并且是唯一的。将两个字段索引在一起的mongoose模式示例是什么?

wgeznvg7

wgeznvg71#

您可以调用Schema对象上的index方法来完成此操作,如下所示。对于您的情况,它将类似于:

mySchema.index({field1: 1, field2: 1}, {unique: true});
dffbzjpn

dffbzjpn2#

在创建复合索引时,必须在架构级别定义索引。

animalSchema.index({ name: 1, type: -1 });

参考:http://mongoosejs.com/docs/guide.html#indexes

1mrurvl1

1mrurvl13#

import { Schema, Document, model } from 'mongoose';

import { IUser } from './User';
import { IMood } from './Mood';
import { ILocation } from './Location';

export interface IUserMoodLocation extends Document {
    userId?: IUser['_id'];
    moodId?: IMood['_id'];
    locationId?: ILocation['_id'];
}

const UserMoodLocationSchema: Schema = new Schema({
    userId: {
        type: Schema.Types.ObjectId,
        required: true,
        ref: 'User'
    },
    moodId: {
        type: Schema.Types.ObjectId,
        required: true,
        ref: 'Mood'
    },
    locationId: {
        type: Schema.Types.ObjectId,
        required: true,
        ref: 'Location'
    }
});

UserMoodLocationSchema.index(
    { userId: 1, moodId: 1, locationId: 1 },
    { unique: true }
);

export const UserMoodLocation = model<IUserMoodLocation>(
    'UserMoodLocation',
    UserMoodLocationSchema
);
unguejic

unguejic4#

Following command can be used to create compound index for nested json:
    db.ACCOUNT_collection.createIndex({"account.id":1,"account.customerId":1},{unique:1}) 
Mongo json structure is like :
{"_id":"648738"
 "account": { 
    "id": "123",
    "customerId": 7879,
    "name": "test"
   ..
   ..

  }
}

我已经用示例数据进行了测试,它完全按预期工作。

t5zmwmid

t5zmwmid5#

顺便说一句,接受的答案是错误的,根据https://stackoverflow.com/a/52553550/129300,您应该用单引号将字段名称括起来,即:

mySchema.index({'field1': 1, 'field2': 1}, {unique: true});

快乐的一天!

相关问题