使用CommonJS创建的Mongoose Schema在移植到Module后不能再工作



我使用如下所示的CommonJS开始我的Mongoose Schema声明,并且填充工作得很好。

对于CommonJS我有:

author.js

const mongoose = require('mongoose');
const AuthorSchema = new mongoose.Schema({
    _id: mongoose.Schema.Types.ObjectId,
    first_name: String,
    last_name: String,
    email: String,
}, {
    timestamps: {
        createdAt: 'created_at',
        updatedAt: 'updated_at'
    }
});
module.exports = mongoose.model('Author', AuthorSchema);

comment.js

const mongoose = require('mongoose');
const CommentSchema = new mongoose.Schema({
    _id: mongoose.Schema.Types.ObjectId,
    text: String,
    author: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'Author'
    }
}, {
    timestamps: {
        createdAt: 'created_at',
        updatedAt: 'updated_at'
    }
});
module.exports = mongoose.model('Comment', CommentSchema);
当使用CommonJS

时,和下面的查询可以完美地工作

let comments = await Comment.find({ author: authorId })
        .populate("author", 'first_name last_name _id').limit(10);

现在,我的团队希望我们从CommonJS转移到模块,所以我将type:module添加到我的package.json文件中,并试图重构上面的模式声明如下:

new_author.js

import mongoose from 'mongoose';
const AuthorSchema = new mongoose.Schema({
    _id: mongoose.Schema.Types.ObjectId,
    first_name: String,
    last_name: String,
    email: String,
}, {
    timestamps: {
        createdAt: 'created_at',
        updatedAt: 'updated_at'
    }
});
export default mongoose.model('Author', AuthorSchema);

new_comment.js

import mongoose from 'mongoose';
const CommentSchema = new mongoose.Schema({
    _id: mongoose.Schema.Types.ObjectId,
    text: String,
    author: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'Author'
    }
}, {
    timestamps: {
        createdAt: 'created_at',
        updatedAt: 'updated_at'
    }
});
export default mongoose.model('Comment', CommentSchema);

,突然下面的查询不再工作

let comments = await Comment.find({ author: authorId })
            .populate("author", 'first_name last_name _id').limit(10);

我一直返回的错误是

MissingSchemaError: Schema hasn't been registered for model "Author".

真是难以置信。正如您在上面看到的,除了使用importsexport default语句之外,没有任何改变。

我认为你的表名可能有问题。尝试更改表名

mongoose.model('newModelName', modelSchema);

相关内容

最新更新