当我点击新闻api时,我似乎总是会收到错误消息
UnhandledPromiseRejectionWarning:TypeError:News.find不是函数
我阅读了Promises,但无法解决此问题。这是猫鼬的东西吗? 我该怎么解决?
我的控制器 NewsController.js
const NewsController = {};
const News = require('../models/news.model');
// await indicates wait for the function to get over.
// we may also use Promises in its place
NewsController.getNews = async function(req, res) {
const allnews = await News.find({}, function(err, ns) {
assert.equal(err, null);
res.json(ns);
});
//res.json(allnews);
};
// ES6 style
NewsController.getSingleNews = async (req, res) => {
const news = await News.findById(req.params.Id);
res.json[news];
};
NewsController.createNews = async (req, res) => {
const news = new News(req.body);
await news.save();
res.json[{
'status': 'item saved successfully'
}];
};
NewsController.deleteNews = async (req, res) => {
await News.findByIdAndRemove(req.params.id);
res.json[{
'status': 'item deleted successfully'
}]
};
module.exports = NewsController;
我的模型 news.model.js
const mongoose = require('mongoose');
const {Schema}= mongoose;
const newsSchema = new Schema({
title: {type: String, required:true},
content:{type: String, required:true},
author:{type: String},
image:{type: String},
source:{type: String}
});
mongoose.exports = mongoose.model('news', newsSchema);
答案 0 :(得分:0)
问题出在mongoose.exports。应该是module.exports谢谢@AnthonyWinzlet
答案 1 :(得分:0)
请查看您的脚本。您出错了,因为您的代码没有函数查找功能。创建它,然后重试。