fix: pass explicit primaryKey to Meilisearch addDocuments/updateDocuments calls

Meilisearch v1.0+ refuses to auto-infer the primary key when a document
contains multiple fields ending with 'id'. The messages index has both
conversationId and messageId, causing addDocuments to silently fail with
index_primary_key_multiple_candidates_found, leaving message search empty.

Pass { primaryKey } to addDocumentsInBatches, addDocuments, and
updateDocuments — the variable was already in scope.

Also replace raw this.collection.updateMany with Mongoose Model.updateMany
to satisfy the no-restricted-syntax ESLint rule (tenant isolation guard).

Closes #12538
This commit is contained in:
Danny Avila 2026-04-03 09:54:54 -04:00
parent b44ce264a4
commit dc7889770a
No known key found for this signature in database
GPG key ID: BF31EEB2C5CA0956

View file

@ -255,7 +255,7 @@ const createMeiliMongooseModel = ({
try {
// Add documents to MeiliSearch
await index.addDocumentsInBatches(formattedDocs);
await index.addDocumentsInBatches(formattedDocs, undefined, { primaryKey });
// Update MongoDB to mark documents as indexed.
// { timestamps: false } prevents Mongoose from touching updatedAt, preserving
@ -422,7 +422,7 @@ const createMeiliMongooseModel = ({
while (retryCount < maxRetries) {
try {
await index.addDocuments([object]);
await index.addDocuments([object], { primaryKey });
break;
} catch (error) {
retryCount++;
@ -436,9 +436,11 @@ const createMeiliMongooseModel = ({
}
try {
await this.collection.updateMany(
const Model = this.constructor as Model<DocumentWithMeiliIndex>;
await Model.updateMany(
{ _id: this._id as Types.ObjectId },
{ $set: { _meiliIndex: true } },
{ timestamps: false },
);
} catch (error) {
logger.error('[addObjectToMeili] Error updating _meiliIndex field:', error);
@ -459,7 +461,7 @@ const createMeiliMongooseModel = ({
const object = _.omitBy(_.pick(this.toJSON(), attributesToIndex), (v, k) =>
k.startsWith('$'),
);
await index.updateDocuments([object]);
await index.updateDocuments([object], { primaryKey });
next();
} catch (error) {
logger.error('[updateObjectToMeili] Error updating document in Meili:', error);