Reputation: 187
I am writing post api using restify and 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()
})
}
}
here error is that Trending is not defined, I don't know why.. other similar controllers are working fine. Trending is mongoose Model model code
'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;
folder structure
controllers
--- trending.js
models
---trending.js
Upvotes: 0
Views: 2639
Reputation: 16579
You are having this problem because of this line;
let Trending = new Trending(data);
You should avoid using the same variable name for two different things to prevent this kind of problem. Especially in this case where you are using uppercase letter for an object when you should use it only for classes.
Replace that line with;
let trending = new Trending(data);
The problem happens because let
(and const
) are block scoped so a variable with the same name but from an outer scope will be overridden. You then get undefined for this variable because you are referencing it in the same line you are declaring it, so it is in fact still undefined.
Upvotes: 2