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.
Related
I can't figure out how to add an SSL certificate to my server.js so I can access my API on the server through https.
var express = require('express'),
cors = require('cors'),
app = express(),
port = process.env.PORT || 3000,
mongoose = require('mongoose'),
Task = require('./api/models/todoListModel'), //created model loading here
bodyParser = require('body-parser'),
helmet = require('helmet');
// Test SSL connection
var MongoClient = require('mongodb').MongoClient;
// mongoose instance connection url connection
mongoose.Promise = global.Promise;
mongoose.connect('mongodb://localhost/Tododb'); // was tododb
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
// adding Helmet to enhance your API's security
app.use(helmet());
// enabling CORS for all requests
app.use(cors());
app.get('/', (req, res) => res.send('Hello World!'))
var routes = require('./api/routes/todoListRoutes'); //importing route
routes(app); //register the route
app.listen(port);
console.log('Supporter RESTful API server started on: ' + port);
I have tried mongoose.connect('mongodb://localhost/Tododb&ssl=true'); but I don't really know what to do after that? I understand I have to add a reference to the key and certificate files that I have generated but I can't figure how I add those to the connection string.
I have been attempting to follow some of this https://docs.mongodb.com/manual/reference/connection-string/
What's the next step?
The next step is to provide ConnectionOptions to the mongoose.connect call. The mongoose documentation (at https://mongoosejs.com/docs/connections.html#options) specifies that it will pass on ssl specific options to the underlying MongoClient. The options for the MongoClient can be found at: http://mongodb.github.io/node-mongodb-native/2.2/api/MongoClient.html#connect
The ones you are interrested in are likely sslCert, sslKey, and maybe sslPass (along with some more of the ssl* settings). Note that the ones I listed here might require you to load in a file in code yourself. You might be able to use something like:
var fs = require('fs');
var options = {
...
sslCert: fs.readFileSync(path.join(__dirname, <relative path to the cert>))
};
mongoose.connect('mongodb://localhost/Tododb', options);
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.
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())
I'm learning the MEAN stack and have found myself with a load order issue that doesn't seem to make sense.
The below code shows my server.js loading the routes file, which in turn pulls in the controller for a model, which in turn requires the model itself.
If I don't include a reference to the model from routes.js I get a MissingSchemeError when I startup the server. Why? Am I missing something regarding the loading of resources?
My understanding was that the exports for a file would be completely imported by the require() prior to attempting to run any code.
server.js
// modules =================================================
var express = require('express');
var bodyParser = require('body-parser');
var methodOverride = require('method-override');
var mongoose = require('mongoose');
var morgan = require('morgan');
var app = express();
// configuration ===========================================
// config files
var db = require('./config/db');
// set our port
var port = process.env.PORT || 8080;
// connect to our mongoDB database
mongoose.connect(db.url);
// get all data/stuff of the body (POST) parameters
// parse application/json
app.use(bodyParser.json());
// parse application/vnd.api+json as json
app.use(bodyParser.json({ type: 'application/vnd.api+json' }));
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: true }));
// override with the X-HTTP-Method-Override header in the request. simulate DELETE/PUT
app.use(methodOverride('X-HTTP-Method-Override'));
// set the static files location /public/img will be /img for users
app.use(express.static(__dirname + '/public'));
// set morgan to log requests
app.use(morgan('dev'));
// routes ==================================================
require('./app/routes')(app);
routes.js
//this line is the problem. why is this needed?
var Customer = require('./models/customer'); // <--
var customers = require('./controllers/customer-server-controller');
module.exports = function(app) {
app.route('/api/customers')
.get(customers.list);
//.post(customer.create);
}
customer-server-controller.js
var mongoose = require('mongoose');
var Customer = mongoose.model('Customer');
/**
* List of Customers
*/
exports.list = function(req, res) {
Customer.find().sort('-created').exec(function(err, customers) {
if (err) {
return res.status(400).send({
message: "ERROR: " + err
});
} else {
res.jsonp(customers);
}
});
};
Got a good portion of the biolerplate from this tutorial on Scotch.io
I take it that you're missing the model from the tutorial
You should have this somewhere.
Create a models folder and add todo.js and add the following:
// define model =================
var Todo = mongoose.model('Todo', {
text : String
});
Your customer-server-controller.js doesn't require() the model file, it just tries to reference the model by asking Mongoose for it (Mongoose doesn't load the model file for you!):
var Customer = mongoose.model('Customer');
You need to require() the module file from your controller, otherwise the model isn't registered with Mongoose and you get the error that you got.
I'm trying to send some data to a database using mongoose. Here is my code so far.
server.js
var express = require('express');
var wine = require('./routes/wines');
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var app = express();
app.use(bodyParser.urlencoded({ extended: true}));
app.use(bodyParser.json());
app.get('/wines', wine.findAll);
app.get('/wines/:id', wine.findById);
app.listen(3000);
console.log('Listening on port 3000...');
wine.js (inside models folder)
var mongoose = require('mongoose');
var db = mongoose.connection;
var wineSchema = new mongoose.Schema({
name: String,
description: String
});
var Wine = mongoose.model('Wine', wineSchema);
module.exports = Wine;
wines.js (inside routes folder)
exports.addWine = function(req, res) {
// Problem not defined here
var silence = new Wine({ name: 'Silence', description:"cena" })
console.log(silence.name) // 'Silence'
// add it to the database
};
I keep getting this error and i have no idea why.
ReferenceError: Wine is not defined
I've exported Wine in wine.js (models), shouldn't I be able to use it everywhere ?
Thank you in advance !
Add var Wine = require('./../models/wine.js'); at the beginning of wines.js (assuming your routes and models folders are contained within the same directory).
Exporting objects/values/functions from node modules does not make them globally available in other modules. The exported objects/values/functions are returned from require (reference here for more info). That said, Mongoose uses an internal global cache for models and schemas which make it available via mongoose (or a connection) throughout an app.
So in your routes file you could do something like:
var Wine = mongoose.model('Wine'); // Notice we don't specify a schema
exports.addWine = function(req, res) {
var silence = new Wine({ name: 'Silence', description:"cena" })
console.log(silence.name) // 'Silence'
// add it to the database
};