【问题标题】:Node Rest API issue with controller控制器的节点休息 API 问题
【发布时间】:2019-09-07 16:43:47
【问题描述】:

我像往常一样开发了我的 node rest api,但这次它在 controller.js 文件中显示了一些无效错误。不需要猫鼬。当我在邮递员中点击 API 时,它给出的错误是:

{ "error": { "message": "Tweets is not a constructor" } }

我什至更新了我的软件包,但似乎没有任何效果。这是我的 tweets.js 控制器的 sn-p:

const mongoose = require('mongoose');
const Tweets = require('../models/tweets');

exports.get_all_tweets = (req, res, next) => {
    Tweets.find()
    .exec()
    .then(docs => {
        console.log(docs);
        res.status(200).json(docs);
    })       
      .catch(err => {
        console.log(err);
        res.status(500).json({
          error: err
        });
      });
}

exports.create_tweets = (req, res, next) => {
    const tweetbody = req.body;
    tweetbody._id = mongoose.Types.ObjectId();
    const tweet = new Tweets(tweetbody);
    tweet
    .save()
    .then(docs => {
        console.log(docs, 'Tweets');
        res.status(200).json(docs);
    })
    .catch(err => {
        console.log(err, 'error found');
        res.status(500).json({
          error:err
        });
    });

第一条 mongoose 行显示为空白,如屏幕截图所示: mongoose

tweets.js 模型:

const mongoose = require('mongoose');

const tweetSchema = mongoose.Schema({
    _id: mongoose.Schema.Types.ObjectId,
    time: { type: String},
    count: { type: Number}
});

module.export = mongoose.model('Tweets', tweetSchema);

【问题讨论】:

  • .exec() 的目的是什么?
  • @narayansharma91 它正在返回一个承诺

标签: node.js rest postman


【解决方案1】:

请在架构初始化之前检查所有路径并添加新关键字

tweets.js 模型:

const tweetSchema = new mongoose.Schema({

【讨论】:

  • 我尝试将它与“新”关键字一起使用。有或没有“新”并没有太大区别。在这两种情况下,最终都会创建新实例。
【解决方案2】:

使用async/await试试这个

exports.get_all_tweets = async (req, res, next) => {
    const result = await Tweets.find()
    res.status(200).json(result);
}

【讨论】:

    【解决方案3】:

    module.exports 结尾有一个 's' :)

    【讨论】:

    • 该死!这样的错字真是太愚蠢了。非常感谢哥们救了我。 :)
    • 我已经有了。但由于我的声誉较低,我的投票没有公开展示。 :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-01-24
    • 2018-04-19
    • 1970-01-01
    • 1970-01-01
    • 2019-12-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多