Мангуст, добавляющий вложенный документ в массив, выдает ошибку _id: this.ownerDocument(…).model не является функцией

#node.js #mongodb #mongoose #subdocument

#node.js #mongodb #mongoose #вложенный документ

Вопрос:

У меня есть две схемы:

 const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const _ = require("lodash");
const { regex } = require("../config/constants");
const { schemaErrors } = require("../config/errors");
const SiaSchema = require("./SiaModel");

const EmployeeSchema = new Schema(
    {
        first_name: {
            type: String,
            required: true,
            trim: true,
        },
        last_name: {
            type: String,
            required: true,
            trim: true,
        },
        mobile: {
            type: String,
            required: true,
            validate: {
                validator: function (v) {
                    return regex.uk.mobile.test(v);
                },
                message: schemaErrors.INVALID_MOBILE,
            },
            trim: true,
        },
        sia: [SiaSchema],
    },
    { timestamps: { createdAt: "created_at", updatedAt: "updated_at" } }
);

EmployeeSchema.statics.addSia = async function (data) {
    let options = { new: true, upsert: true, runValidators: true };
    let sia = Object.assign({}, data);
    delete sia._id;
    let orQuery = [];
    for (const attribute in sia) {
        orQuery.push({ [`sia.${attribute}`]: sia[attribute] });
    }
    let existing = await this.findOne({ $or: orQuery });
    if (existing) return Promise.resolve(existing);
    
    return this.findByIdAndUpdate(data._id, { $push: { sia: sia } }, options);
};

module.exports = EmployeeSchema; // I am not exporting mongoose model here because model creation for all schemas is being handled by another module
  

и

 const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const _ = require("lodash");
const { regex } = require("../config/constants");
const { schemaErrors } = require("../config/errors");
const SiaSchema = new Schema(
    {
        sia_number: {
            type: String,
            required: true,
            validate: {
                validator: function (v) {
                    return regex.uk.sia.test(v);
                },
                message: schemaErrors.INVALID_SIA_NUMBER,
            },
        },
        issue_date: {
            type: Date,
            required: true,
            validate: {
                validator: function (v) {
                    return v instanceof Date amp;amp; v.getTime() < Date.now();
                },
                message: schemaErrors.INVALID_ISSUE_DATE,
            },
        },
        expiration_date: {
            type: Date,
            required: true,
            validate: {
                validator: function (v) {
                    return v instanceof Date amp;amp; v > this.issue_date;
                },
                message: schemaErrors.INVALID_EXPIRATION_DATE,
            },
        },
    },
    { timestamps: { createdAt: "created_at", updatedAt: "updated_at" } }
);

module.exports = SiaSchema; // I am not exporting mongoose model here because model creation for all schemas is being handled by another module
  

Я создал Employee. Затем я вызвал другой API, чтобы добавить Sia для этого сотрудника, используя статический метод addSia, определенный в схеме Employee, но он выдает мне следующую ошибку:

"Validation failed: sia: Validation failed: _id: this.ownerDocument(...).model is not a function".

Это тело API и данные, передаваемые в качестве data параметра методу addSia:

 {
    "_id": "5f36cde0e4c4163838674219", // ID of the employee for whom I want to add sia
    "sia_number": "0000000000000000",
    "issue_date": "2020-08-01",
    "expiration_date": "2025-08-01"
}
  

Если я удаляю runValidators: true из options в методе addSia, функция работает, но проверки не применяются.

Я был бы очень признателен за любую помощь в этом.

Node.js версия 11.9.0

Версия Mongoose 5.9.28

Mongodb версии 4.2.3

Комментарии:

1. У меня было точно такое же сообщение об ошибке, и я обнаружил, что проблема заключается в плагине, который я использовал. Этот плагин является mongoose-unique-validator .