0

this is my schema for Mongodb:

import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose';
import { MinioBucket } from '../../../common/enums';
import { Document } from 'mongoose';

@Schema({ versionKey: false, timestamps: true })
export class Column extends Document {
  @Prop({ type: String, required: true })
  tableCol: string;
  @Prop({ type: String, required: true })
  sheetCol: string;
}
const ColumnSchema = SchemaFactory.createForClass(Column);

@Schema({ versionKey: false, timestamps: true })
export class Col extends Document {
  @Prop({ type: String, required: true, unique: true })
  public readonly provider!: string;

  @Prop({ type: [ColumnSchema] })
  cols: Column[];
}

const ColSchema = SchemaFactory.createForClass(Col);

ColSchema.index({ provider: 1 });
export { ColSchema };

in database I saved: { provider: "abc", columns: [ {"tableCol": "name" "sheetCol": "Name"} ] }

Now when I want to add another provider, but with the same columns name I recieve the error: ERROR [ExceptionsHandler] E11000 duplicate key error collection: xxx.columns index: columns.tableCol_1 dup key: { columns.tableCol: "name" } MongoServerError: E11000 duplicate key error collection: xxx.columns index: columns.tableCol_1 dup key: { columns.tableCol: "name" }

Data I want to add: { provider: "cde", columns: [ {"tableCol": "name" "sheetCol": "Name"} ] }

I tried to put {unique: false}, and I found on internet about {spars: true}, but it didn't help

And I cannot drop the Index, I need to have both data in database

1
  • I don't think I understand the comment that you can't drop the index. If the index has a unique constraint applied to it that you don't want, then you will have to drop it Commented Mar 24, 2023 at 18:00

1 Answer 1

0

If you drop the index – it will not drop data in the database.

You need to create a compound index for both provider and cols.tableCol fields.

To do so, first, create a compound idex:

ColSchema.index({ provider: 1, 'cols.tableCol': 1 }, { unique: true });

Then, drop the old index.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.