Javascript 节点js中未定义模型错误
我正在使用restify和mongodb与mongoose一起编写PostAPIJavascript 节点js中未定义模型错误,javascript,node.js,mongoose,restify,Javascript,Node.js,Mongoose,Restify,我正在使用restify和mongodb与mongoose一起编写PostAPI 'use strict' const Trending = require('../models/trending'); const trendingController = { postTrending: (req, res, next)=>{ let data = req.body || {}; console.log(Trending); l
'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
)是块作用域,因此将覆盖来自外部作用域的同名变量。然后,由于在声明该变量的同一行中引用该变量,因此该变量未定义,因此它实际上仍然未定义。由于这一行,您遇到了此问题
let Trending = new Trending(data);
您应该避免对两个不同的事物使用相同的变量名,以防止此类问题。特别是在这种情况下,当您只应将大写字母用于类时,您将使用大写字母作为对象
将该行替换为
let trending = new Trending(data);
出现此问题的原因是
let
(和const
)是块作用域,因此将覆盖来自外部作用域的同名变量。然后,由于您在声明该变量的同一行中引用该变量,因此该变量没有定义,因此实际上它仍然没有定义。发布趋势代码和path@Sajeetharan我编辑了一篇博文你到底是怎么发布你的趋势的?因为我真的看不出你在哪里为它创建了一条路线path@Sajeetharan我编辑了一篇博文你到底是怎么发布你的趋势的?因为我真的看不出你在哪里为它创建了路线。