【问题标题】:model in not defined error in node js节点js中的模型未定义错误
【发布时间】:2018-04-08 14:06:51
【问题描述】:

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

'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

【问题讨论】:

  • 贴出趋势代码和路径
  • @Sajeetharan 我编辑了帖子
  • 你究竟是如何发布你的趋势的?因为我真的看不出你在哪里为此创建了一条路线。

标签: javascript node.js mongoose restify


【解决方案1】:

由于这条线,您遇到了这个问题;

let Trending = new Trending(data);

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

将该行替换为;

let trending = new Trending(data);

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

【讨论】:

    猜你喜欢
    • 2018-07-14
    • 2019-03-30
    • 2017-11-01
    • 2017-06-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多