Я изучаю средний стек и когда я пытаюсь запустить использование сервера
npm start
Я получаю исключение, говоря что:
schema hasn't been registered for model 'Post'. Use mongoose.model(name, schema)
вот мой код внутри/models/Posts.js
var mongoose = require('mongoose');
var PostSchema = new mongoose.Schema({
title: String,
link: String,
upvotes: { type: Number, default: 0 },
comments: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Comment' }]
});
mongoose.model('Post', PostSchema);
поскольку я вижу, что схема должна быть зарегистрирована для модели 'Post', но что может возможно заставлять исключение быть брошенным?
Заранее спасибо.
Править: Вот ошибка исключения
/home/arash/Documents/projects/personal/flapper-news/node_modules/mongoose/lib/index.js:323
throw new mongoose.Error.MissingSchemaError(name);
^
MissingSchemaError: Schema hasn't been registered for model "Post".
Use mongoose.model(name, schema)
и вот код app.js с инициализацией мангусты:
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/news');
require('./models/Posts');
require('./models/Comments');
перед строкой:
app.use('/', routes);
Я использовал следующий подход для решения выпуска
const mongoose = require('mongoose');
const Comment = require('./comment');
const PostSchema = new mongoose.Schema({
title: String,
link: String,
upvotes: { type: Number, default: 0 },
comments: [{ type: mongoose.Schema.Types.ObjectId, ref: Comment }]
});
mongoose.model('Post', PostSchema);
, посмотрите, здесь ref
не имеют string
значение типа, теперь это относится к Comment
схема.
Эта ошибка также открывается, когда мы создаем неправильные ссылки (касательно) между моделями мангусты.
В моем случае я обращался к имени файла вместо имени модели.
, например:
константа userModel = mongoose.model ("пользователь", userSchema);
Мы должны обратиться к 'пользователю' (имя модели) вместо 'Пользователя' (имя файла);
.\nodeapp\node_modules\mongoose\lib\index.js:452
throw new mongoose.Error.MissingSchemaError(name);
^
MissingSchemaError: Schema hasn't been registered for model "users".
Use mongoose.model(name, schema)
at new MissingSchemaError
я разрешил эту ошибку когда использование setTimeout на server.js
mongoose.connect(env.get('mongodb.uri'), { useNewUrlParser: true })
.then(() => logger.info("MongoDB successfully connected"))
.catch(err => logger.error(err));
app.use(passport.initialize());
setTimeout(function() {
require("./src/utils/passport")(passport);
}, 3000);
В моем случае, эта проблема, потому что я не включал модель или касательно модели в приложение. Таким образом, Вы должны требуемый Post model
и Comment model
в Вашем приложении узла.
Отошлите то же имя, которое Вы отсылаете в имени модели при создании новой модели.
, Например: если у меня есть модель мангусты как:
var Post = mongoose.model("post",postSchema);
Затем я должен обратиться к набору сообщений через запись ref:"post"
.
Вот https://mongoosejs.com/docs/populate.html#cross-db-populate
, Он говорит, что мы должны передать модель как третий аргумент.
Для, например,
//Require User Model
const UserModel = require('./../models/User');
//Require Post Model
const PostModel = require('./../models/Post');
const posts = await PostModel.find({})
.select('-__v')
.populate({
path: 'user',
select: 'name -_id',
model: UserModel
});
//or
const posts = await PostModel.find({})
.select('-__v')
.populate('user','name', UserModel);