mongoose is not defined - node.js

I'm following this tutorial, which creates a To-do list using express and mongo. I am getting the following errors:
body-parser deprecated undefined extended: provide extended option server.js:12:20
C:\todoListApi\api\controllers\todoListController.js:4
var Task = mongoose.model('Tasks');
^
ReferenceError: mongoose is not defined
at Object.<anonymous> (C:\todoListApi\api\controllers\todoListController.js:4:12)
...
The body-parser deprecated error I have tried to fix using this post to no avail (although it seems like more of a warning).
The mongoose error doesn't make any sense because mongoose ids defined directly before it:
var mongooose = require('mongoose').Mongoose,
Task = mongoose.model('Tasks');
But it's also defined in server.js:
var express = require('express'),
app = express(),
port = process.env.PORT || 3000,
mongoose = require('mongoose'),
Task = require('./api/models/todoListModel'),
bodyParser = require('body-parser');
mongoose.Promise = global.Promise;
mongoose.connect('mongodb://localhost/Tododb');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.urlencoded(bodyParser.json()));
var routes = require('./api/routes/todoListRoutes');
routes(app);
app.listen(port);
console.log('todo list RESTful API server started on: ' + port)
I changed this from the original tutorial to add .Mongoose because this post said it would work.

As stated by Jérôme in his comment, your mongoose variable is being defined as mongooose but then being accessed throughout your code as mongoose without the 3rd o.
As for the body parser issue, you don't wrap bodyParser.json() within the bodyParser.urlencoded() middleware. bodyParser.json() is returning its own middleware function that needs to be passed directly to the express server.
app.use(bodyParser.urlencoded({extended: true})
app.use(bodyParser.json())

Related

I have problems to run server.js in terminal

enter image description here[
// Setup empty JS object to act as endpoint for all routes
projectData = {};
// Require Express to run server and routes
const express = require('express');
const app = express();
// Start up an instance of app
const PORT = 8080;
app.listen(PORT, () => {
console.log('Hi');
console.log(`the port that we will use is ${port}`);
});
/* Middleware*/
//Here we are configuring express to use body-parser as middle-ware.
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
// Cors for cross origin allowance
app.use(cors());
// Initialize the main project folder
app.use(express.static('website'));
// Setup Server
app.post('/link', function(req,res) {
});
What should i do to run this in terminal
*I tried alot of solutions bot it's not working
in the terminal[
1.
it can not find the file
]3*
I think you need to install the 'body-parser' library and send it to call in your file
npm install body-parser
const bodyParser = require('body-parser');
app.use(bodyParser.json());
You don't need to use bodyparser if you use latest or after 4.0 version of Express.js. You can use
app.use(express.json()) // Parse Json Bodies
app.use(express.urlencoded()); //Parse URL-encoded bodies
as middlewares instead, without any package. They will solve your problem.

Using mongoose in multiple routes with express

I have set up my code in server.js which worked fine. I am now trying to clean up the server.js code by splitting the code into different routes.
I am using the express.Router to link up the files but i am struggling to understand why my post route is braking.
In the server.js file
// dependencies
const express = require("express");
const bodyParser = require("body-parser");
const app = express();
app.use(bodyparser.urlencoded({extended: true}));
app.set('view engine', 'ejs');
// routes
constpurchaseOrders = require("./routes/purchaseOrders");
app.use("/purchaseOrders", purchaseOrders);
// listen
app.listen(3000, function(){
console.log("Server started on port 3000");
});
In the purchaseOrders.js file
// dependencies
const express = require("express");
let router = express.Router();
const mongoose = require("Mongoose");
const connection = require("../routes/mongoose.js");
const Po = require("../routes/schemas.js:);
// post route
router.post("/addpo, function(req.res){
//long code lines here
po.save();
res.redirect("/");
});
module.exports = router;
So with this route, i have the following end point on the route.get:
10.0.0.15:3000/purchaseOrders/addpo
Now the problem comes in when i submit the form, it returns "cannot POST /addpo" and the end point shows:
10.0.0.15:3000/addpo
On my ejs file i have set the form up as follows:
<form action="/addpo" method="post">
On the mongoose.js connection i export as follows:
module.exports = mongoose;
On the schemas.js i export:
module.exports = Po;
I know I did something wrong with the routing but i cannot figure our why.
Thanks alot :-)
if you need the /addpo path to work, change this on server.js:
app.use("/", purchaseOrders);
NOT
app.use("/purchaseOrders", purchaseOrders);
Other option
server.js:
app.use("/addpo", purchaseOrders);
purchaseOrders.js
router.post("/", function(req.res){
If you add a route before calling a router it will be added in front of it.
So, yo can use the route action="/addpo" in the html.
Express docs

What does mean "var router = require('./router/main')(app)"?

(I know that there is a similar question in stackoverflow, but I can't understand that question's comment..)
I'm Korean middle schooler.
So I am not good at English but Please help me.
I'm studying Node.js and Express.js by example codes.
This is example code which I'm looking at.
var express = require("express");
var app = express();
var bodyParser = require("body-parser");
var session = require("express-session");
var fs = require("fs");
app.set("views", __dirname + "/views");
app.set("view engine", "ejs");
app.engine("html", require("ejs").renderFile);
var server = app.listen(3000, function() {
console.log("Express server has started on port 3000");
});
app.use(express.static("public"));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded());
app.use(session({
secret: '##SEC$$RET##',
resave: false,
saveUninitialized: true
}));
var router = require("./router/main")(app, fs)
I have understood majority of this code, but I cannot understand "(app, fs)" at last line.
What does that mean??
I'll appreciate your kindness if you help me .. ㅠㅠ
This means that ./router/main module exports factory function that accepts application instance and fs module as parameters and returns router instance that depends on these parameters, e.g.:
var express = require('express');
module.exports = (app, fs) => {
var router = express.Router();
// define router routes that make use of `app` and `fs`
return router;
};
This way router factory function basically implements dependency injection pattern.
app parameter is a common Express recipe to pass application instance to a router, while passing fs is unneeded. fs module could be imported directly in ./router/main module, it doesn't benefit much from dependency injection.
It imports the router from that file. The router requires you to pass 2 parameters - the app and fs. It's the same as calling a regular function. Just here, it is importing the route and calling the function in one place.

Node.js argument type string is not assignable to parameter type function(T)

I learn Node.js. I started to create my first app with API.
What means the error on the tooltip? (see the image) I have seen it for the first time.
My code:
const express = require('express'),
app = express(),
bodyParser = require('body-parser'),
mongoose = require('mongoose'),
morgan = require('morgan'),
consign = require('consign'),
cors = require('cors'),
passport = require('passport'),
passportConfig = require('./passport')(passport),
jtw = require('jsonwebtoken'),
config = require('./index.js'),
database = require('./database')(mongoose, config);
app.use(express.static('.'));
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(morgan('dev'));
app.use(cors());
app.use(passport.initialize());
app.set('medsecret', config.secret);
consign({ cwd: './services' })
.include('../API/app/setup')
.then('../API/app/api')
.then('API/app/routes')
.into(app);
module.exports = app;
You may ignore this tooltip, if then is an innate feature of consign module. Essentially, for the editor you're using, then chain is being interpreted by it as set of promises, and since you cannot merely pass strings as an argument to promises in the fashion like this, it displays false error.
Rest assured, if it doesn't lead to a loss of functionality, it is acceptable. You may ignore this tooltip for now.
Alternatively, you may try to install the ts defintions of the same, and then see if the erroneous tooltip vanishes.

nodejs: complaining about an used model

I was following this tutorial https://www.codementor.io/olatundegaruba/nodejs-restful-apis-in-10-minutes-q0sgsfhbd for building my first api.
Everything worked fine, and then I decided to change it to store locations and favorites, created a FavoritesModel.js and a LocationsModel.js.
My server.js now has
var express = require('express'),
app = express(),
port = process.env.PORT || 3000,
mongoose = require('mongoose'),
Location = require('./api/models/LocationsModel'),
Favorite = require('./api/models/FavoritesModel'),
bodyParser = require('body-parser');
mongoose.Promise = global.Promise;
mongoose.connect('mongodb://localhost/db');
require("./api/models/LocationsModel");
require("./api/models/FavoritesModel");
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
var routes = require('./api/routes/geolocationAPIRoutes');
routes(app);
app.listen(port);
console.log('geolocation RESTful API server started on: ' + port);
app.use(function(req, res) {
res.status(404).send({url: req.originalUrl + ' not found'})
});
However, when i run npm run start, i get MissingSchemaError: Schema hasn't been registered for model "Tasks".
What am I doing wrong? There's no reference for Tasks anywhere anymore. Do I need to rebuild the API or something? I already did a npm rebuild.
Location = require('./api/models/LocationsModel'), // remove this
Favorite = require('./api/models/FavoritesModel'), // remove this
bodyParser = require('body-parser');
mongoose.Promise = global.Promise;
mongoose.connect('mongodb://localhost/db');
var Location = require("./api/models/LocationsModel");// change this
var Favorite = require("./api/models/FavoritesModel");// change this
You requires those models twice.
Remove those requires before connect. And sentence variables after connection.

Resources