我使用如下所示的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".
真是难以置信。正如您在上面看到的,除了使用imports
和export default
语句之外,没有任何改变。
我认为你的表名可能有问题。尝试更改表名
mongoose.model('newModelName', modelSchema);