How to connect Mongo DB in a webpack dev server - node.js

I would like to connect to Mongo DB using a webpack dev server. While the connection using the node mongodb driver and configuring in server.js is direct and straight forward, I am thinking of a way to do the same using webpack dev server in development (mainly for the hot loading advantage).
I understand that there is a way of achieving the same using a webpack middleware, but is there another easier and better way of doing it.

webpack dev-server is generally a simple Express or similar node.js server. It's essentially exactly the same as writing is on an express.js server.
npm install mongoose mongodb --save-dev
const mongoose = require('mongoose'); // Replace with import as desired
const mongoConnectString = 'mongodb://localhost/database-name-here';
mongoose.connect(mongoConnectString, (err) => {
if (err) {
console.log('Err, could not connect to the database.');
}
});
Replace the mongoConnectString as needed for developing or using databases that aren't local to your machine.

Related

How to publish a API project with heroku?

I try to publish an API application with Heroku but I am getting an error. What could be the reason? I might be doing something missing. Can you show me what I'm missing?
heroku logs --tail Result
Application index
edit:
I dont have your code snippet so i'm just giving my example here for local development and heroku setup both
In local development
install dotenv npm package
create .env file in root directory and set MONGOURI='Your mongo string here'
then you can import dotenv package in root as shown in below example and use variable as process.env.MONGOURI
On Heroku
there are multiple ways you can do same thing as above which are listed here in config vars. More specifically i'll suggest you to do this way from heroku frontend
require('dotenv').config(); // <-- install `dotenv` package
const MongoClient = require('mongodb').MongoClient;
const mongoUrl = process.env.MONGOURI;
// Connect to the db
MongoClient.connect(mongoUrl, function (err, db) {
if(err) throw err;
db.open(function(err, mongoClient) {
console.log("mongo connected");
});
db.close();
});
I had created a node with mongo boilerplate project to get me started you can check if you want node-auth-mongo

deploy module to remote server that is running node.js

I'm working on my app.js in node.js
-- trying to deploy server-side script.
Many fine node.js modules need a require('something');
I use NPM locally, which works for require, as modules are nicely visible in the local node_modules folder structure. but now I'm ready to upload or bundle to a host. I can't run npm on this hosted server.
const Hapi = require('hapi');
will result in
Error: Cannot find module 'hapi'
because I don't know how to copy/install/bundle/ftp files to my host.
Hapi is just an example. Most anything that has a require will need something on the host.
I used webpack to create a server side bundle.js but just sticking bundle.js under /node_modules doesn't do anything.
Most modules have a complex folder structure underneath --- I'm trying to avoid copying a ton of folders and files under /node_modules. Ideally, I want to combine the modules into a bundle.js and have those modules visible to app.js
but I am open to other ideas.
I have not yet tried using webpack to bundle app.js TOGETHER with the various modules. Have you had luck with that approach?
thanks.
I've tried to upload hapi files a folder-ful at a time, reaching a new require('something') error at every step.
'use strict';
const Hapi = require('hapi'); // <-- how can I deploy hapi on my node.js server?
// Create a server with a host and port
const server=Hapi.server({
host:'localhost',
port:8000
});
// Add the route
server.route({
method:'GET',
path:'/hello',
handler:function(request,h) {
return'hello world';
}
});
// Start the server
async function start() {
try {
await server.start();
}
catch (err) {
console.log(err);
process.exit(1);
}
console.log('Server running at:', server.info.uri);
};
start();
one approach that worked: using webpack to bundle the back end js.
thanks to
https://medium.com/code-oil/webpack-javascript-bundling-for-both-front-end-and-back-
end-b95f1b429810
the aha moment... run webpack to create bundle-back.js then
tie bundle-back.js to my node server
**You start your backend server with ‘bundle-back.js’ using:
node bundle-back.js
In other words, include app.js in the bundle with the modules.

Dependance Sequelize

I try to use Sequelize .. And I have problems :( . I don't know if I have a conflict with an other npm package ..
Like the tuto, I did :
npm install sequelize --save
npm install mysql2 -- save
In my react app, in "sequelizeYes" folder, I did :
import * as Sequelize from 'sequelize'
const seq = new Sequelize('galadat', 'root', '')
seq
.authenticate()
.then(() => {
console.log('Connection has been established successfully.');
})
.catch(err => {
console.error('Unable to connect to the database:', err);
});
export default seq
In app component, i call the file like this :
import('../sequelizeYes')
You can see on the picture differents errors in the console..
Do you have an idea ?
Did you require the module?
var Sequelize = require('sequelize');
var fs = require('fs');
If you shared the lines of code that the errors indicate it might help as well. It looks like several different files are having problems.
Sequelize is a nodejs module intended to be used in your backend. (server-side) It will not work on client-side (with libraries such as React) as it has dependencies to native NodeJS modules as based on your description that is what you're trying to do. If you're working on a web application and use for example express have a look here https://github.com/sequelize/express-example
As #Eric suggests, you should require sequelize on top of your code. So this should work:
var Sequelize = require('sequelize');
If the error persists, you should delete folder "node_modules" and reinstall dependencies using the command "npm install". Also you should make sure all errors are thrown because of sequelize import.
If the error still persists, you should make sure you try to manipulate the models in server-side code, as #archansel and #frenzzy suggest here: https://github.com/kriasoft/react-starter-kit/issues/976
The reason is referenced above by #razakj answer

Grunt and express.js server

Currenty I'm using grunt with karma and jasmine to run my tests etc. for my Angular app.
I want to connect this app to a mongo database and was wondering what the best way to do this is. Should I keep using grunt and just connect to a database and use it all the way, or should I use an Express server as my main server connected to the database and run the tests with grunt?
Initially I want to publish this project to heroku, and I know you can do this by just adding a static server.js (wich I do not currently have) like this.
var express = require('express');
var port = process.env.PORT || 3000;
var app = express();
app.use(express.static(__dirname + ‘/public’));
app.listen(port);
and modify the gruntfile.js with this:
tasks
grunt.registerTask('heroku',
['compass:dist', 'autoprefixer', 'imagemin']);
What is the best way to do this?
I see, I feel you have slight misconception of what grunt is. Grunt is a task runner. It will run other commands when for each task. Say for example if you can compile css or minifiy js or combine images before starting server you can do it with grunt. But that does not mean grunt can do all those by itself. It will be using other libraries for those.
If you are using grunt to do testing you internally using jasmine or karma js or something else. Same when you say grunt serve you use express internally start server. So grunt does not connect to mongodb. It is express which connects to mongodb. You can write grunt tasks which will start mongodb and start express server but grunt can not do either by its own.
Should you use grunt? Yes of course.

Node.js and Mongodb

So i am trying to use Node.js and Mongodb together and the goal is to use Node to get information and store it in a database with Mongodb. SO I have both Node and Mongdb intalled, and I install the Mongodb package with npm, this is the package mongodb recommends. But the problem I am having is that when I try to do
MongoClient.connect("mongodb://localhost:3000/exampleDb", function(err, db) {
if(err) { return console.dir(err); }else{
var collection =db.createCollection('test', function(err, collection) {}); }});
and I go to localhost:port_for express_server, but when the above code is supposed to run I get [Error: failed to connect to [localhost:3000]] in the Node console.Am I supposed to be running mongodb in the background or how is this supposed to work?
when you do
npm install mongodb
you only install a node.js client driver for mongodb.
in order for you script to run, you need to install and start a mongodb server on your box
check server installation procedures on http://docs.mongodb.org/manual/installation/
You seem pretty lost on what mongodb is and how to use it. Mongodb is a noSQL database.
Am I supposed to be running mongodb in the background
Yes, like mysql, you need the server to be installed and running, to use it. You need to do:
mongodb (the db server)
install server
start the server by typing mongod on terminal
check with mongo if it is running and you can connect to it.
node.js (the web server)
install node
install mongodb package
now test your code

Resources