Почему Mongoose 5.7 нарушил клонирование схемы? - PullRequest
0 голосов
/ 30 октября 2019

У меня есть уже существующий модуль для клонирования схемы, который используется для резервного копирования веб-страниц (например, система CMS). Когда я обновился до mongoose 5.7.5, клонирование схемы прервалось.

это модуль клонирования:

module.exports = function (schema, mongoose) {
'use strict';

mongoose = mongoose || require('mongoose');

let clonedSchema = new mongoose.Schema();

schema.eachPath(function (key, path) {
    if (key === '_id') {
        return;
    }

    let clonedPath = {};

    clonedPath[key] = path.options;
    delete clonedPath[key].unique;

    clonedSchema.add(clonedPath);
});

return clonedSchema;
};

это клонирование схемы

let pageSchema = new Schema({
title: {
    type: String,
    required: true
},
translateKey: {
    type: String,
    required: true
},
lang: {
    type: String,
    required: true
}
},
{
timestamps: true
});

Он ломается на clonedSchema.add(clonedPath) с первым путем, который пытается добавить.

ОШИБКА

UnhandledPromiseRejectionWarning: MongooseError: Invalid ref at path "title". Got null
at new MongooseError (/node_modules/mongoose/lib/error/mongooseError.js:10:11)
at validateRef (/node_modules/mongoose/lib/helpers/populate/validateRef.js:17:9)
at Clone.Schema.path (/node_modules/mongoose/lib/schema.js:577:5)
at Clone.add (/node_modules/mongoose/lib/schema.js:442:12)
at Schema.extend (/node_modules/mongoose-schema-extend/index.js:81:13)
at /api/common/lib/clone-schema.js:19:22
at Schema.eachPath (/api/node_modules/mongoose/lib/schema.js:934:5)
at module.exports (/api/common/lib/clone-schema.js:9:12)
at Object.<anonymous> (/api/common/schemas/Page.schema.js:39:23)
at Module._compile (module.js:652:30)
at Object.Module._extensions..js (module.js:663:10)
at Module.load (module.js:565:32)
at tryModuleLoad (module.js:505:12)
at Function.Module._load (module.js:497:3)
at Module.require (module.js:596:17)
at require (internal/module.js:11:18)

Я сделал сравнение schema, переданного в этот модуль между mongoose 5.5.2 и5.7.5. Единственное отличие в 5.7.5 состоит в том, что $immutable теперь является включенным свойством

title: 
  SchemaString {
    enumValues: [],
    regExp: null,
    path: 'title',
    instance: 'String',
    validators: [Array],
    getters: [],
    setters: [],
    options: [Object],
    _index: null,
    '$immutable': null,
    isRequired: true,
    requiredValidator: [Function],
    originalRequiredValue: true,
    [Symbol(mongoose#schemaType)]: true },
 translateKey: 
  SchemaString {
    enumValues: [],
    regExp: null,
    path: 'translateKey',
    instance: 'String',
    validators: [Array],
    getters: [],
    setters: [],
    options: [Object],
    _index: null,
    '$immutable': null,
    isRequired: true,
    requiredValidator: [Function],
    originalRequiredValue: true,
    [Symbol(mongoose#schemaType)]: true }

Я пробовал "npm mongoose-schema-extended", но это дало мне TypeError: Method Map.prototype.has called on incompatible receiver [object Map]. Поэтому не уверен, как его использовать здесь.

const extend = require('mongoose-schema-extend');

let clonedSchema = new mongoose.Schema();

schema.eachPath(function (key, path) {
    if (key === '_id') {
        return;
    }

    let prop = {};
    prop[key] = path;
    clonedSchema.extend(prop);
});

Я бросил попытку / ловлю в модуль, чтобы посмотреть, будет ли это что-нибудь делать. Нет.

Я также удалил каталог node_modules и переустановил плагины.

Я также добавил useUnifiedTopology: true в инициализацию Mongoose для потомков.

Кто-нибудь знает, что изменилосьв 5.7 сломать это?

...