节点js中未定义错误的模型

model in not defined error in node js

我正在写 post api 使用 restify 和 mongodb with mongoose。

'use strict'

const Trending = require('../models/trending');

const trendingController = {
    postTrending: (req, res, next)=>{

        let data = req.body || {};
        console.log(Trending);
        let Trending = new Trending(data);
        Trending.save(function(err) {

            if (err) {
                console.log(err)
                return next(new errors.InternalError(err.message))
                next()
            }

            res.send(201)
            next()

        })

    }
}

这里的错误是没有定义趋势,我不知道为什么..其他类似的控制器工作正常。 趋势是猫鼬模型 型号代码

'use strict'

const mongoose = require('mongoose');
const timestamps = require('mongoose-timestamp');
const Schema = mongoose.Schema;
const TrendingSchema = new mongoose.Schema({
    _id: Schema.Types.ObjectId,
    headline: {
      type: String,
      required: true
    },
    description: String,
    data: [
      {
          heading: String,
          list: [String]
      }
    ],
    tags: [{ type: Schema.Types.ObjectId, ref: 'Tags' }]
});

TrendingSchema.plugin(timestamps);

const Trending = mongoose.model('Trending', TrendingSchema)
module.exports = Trending;

文件夹结构

controllers
--- trending.js
models
---trending.js

你遇到这个问题是因为这条线;

let Trending = new Trending(data);

您应该避免对两个不同的事物使用相同的变量名,以防止出现此类问题。特别是在这种情况下,当您应该仅将大写字母用于 类.

时,您将大写字母用于对象

将该行替换为;

let trending = new Trending(data);

问题的发生是因为 let(和 const)是块作用域的,因此具有相同名称但来自外部作用域的变量将被覆盖。然后你得到这个变量的未定义,因为你在声明它的同一行中引用它,所以它实际上仍然是未定义的。