raspberry pi mongodb help connecting - javascript

So I am just gettting into web dev and as i've been following along with colt steele's course on udemy. The class is going swell and I am building my own website on the side which I am trying to host on a raspberry pi 4 (I have a 32 bit version as well as the new 64 bit version). I have the web app and database working fine locally on my win10 laptop, but I cannot get the app to work on my pi. I am using Node v12.18.3, express v4.17.1, and mongodb v4.4 (shell and server, win10 machine), and mongodb v2.4.14(raspberry pi).
the problem I seem to be having is connecting to the mongo database. I think this is cause I'm using mongoose to try to connect to mongodb but mongoose wont support mongodb version 2.4.14.
this is my code that works on my win 10 machine to connect:
mongoose.connect('mongodb://localhost:27017/Fries-and-Ketchup', { useNewUrlParser: true, useUnifiedTopology: true, useFindAndModify: false });
mongoose.connection.on('connected', () => {
console.log('connected to mongoDB');
});
mongoose.connection.on('error' , err => {
console.log('error connecting to mongodb');
});
this is the error i get in my terminal:
(node:31771) UnhandledPromiseRejectionWarning: MongoServerSelectionError: Server at localhost:27017 reports maximum wire version 0, but this version of the Node.js Driver requires at least 2 (MongoDB 2.6)
at Timeout._onTimeout (/home/pi/Fries_and_ketchup/node_modules/mongodb/lib/core/sdam/topology.js:438:30)
at listOnTimeout (internal/timers.js:549:17)
at processTimers (internal/timers.js:492:7)
(node:31771) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:31771) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
so I tried using a different piece of code I found but unfortunately this doesnt work either:
const MongoClient = require("mongodb").MongoClient;
const url = "mongodb://10.0.0.109:27017";
MongoClient.connect("mongodb://localhost:27017/Fries-and-ketchup", {
useNewUrlParser: true,
useUnifiedTopology: true
})
how can I connect to the Mongo database on the Pi?

Try
const {MongoClient} = require('mongodb');
const url = "mongodb://127.0.0.1:27017/Fries-and-ketchup";
const client = new MongoClient.connect(url, { useNewUrlParser: true, useUnifiedTopology: true });
Since MongoClient is a class, you need to declare it with new

you are doing it rigth, but please check your mongodb version with :
mongo --version
if this version is < 3.1.0 update your mongo version to => 3.1.0 and use this connection code:
MongoClient.connect("mongodb://localhost:27017/Fries-and-ketchup", {
useNewUrlParser: true,
useUnifiedTopology: true
})
or even use mongoose driver, if you want to keep your actual mongo db version(2.x.x), try to connect like this:
var MongoClient = require('mongodb').MongoClient;
MongoClient.connect('mongodb://localhost:27017/Fries-and-ketchup', function(err, db) {console.log("connect",db)});

Related

how to solve error: MongoNetworkError: connect ECONNREFUSED ::1:27017 when trying mongodb compass connection [duplicate]

I have just started learning about MongoDB and I am trying to host my node js application locally via MongoDB Server 6.0 (without using mongoose or atlas)
I copied the async javascript code given in the MongoDB docs. I made sure to run mongod before executing the below code
MongoDB server started
const { MongoClient } = require("mongodb");
// Connection URI
const uri =
"**mongodb://localhost:27017**";
// Create a new MongoClient
const client = new MongoClient(uri);
async function run() {
try {
// Connect the client to the server (optional starting in v4.7)
await client.connect();
// Establish and verify connection
await client.db("admin").command({ ping: 1 });
console.log("Connected successfully to server");
} finally {
// Ensures that the client will close when you finish/error
await client.close();
}
}
run().catch(console.dir);
It's throwing an error:
image of the error it's throwing
Problem is, the localhost alias resolves to IPv6 address ::1 instead of 127.0.0.1
However, net.ipv6 defaults to false.
The best option would be to start the MongoDB with this configuration:
net:
ipv6: true
bindIpAll: true
or
net:
ipv6: true
bindIp: localhost
Then all variants should work:
C:\>mongosh "mongodb://localhost:27017" --quiet --eval "db.getMongo()"
mongodb://localhost:27017/?directConnection=true&serverSelectionTimeoutMS=2000&appName=mongosh+1.6.0
C:\>mongosh "mongodb://127.0.0.1:27017" --quiet --eval "db.getMongo()"
mongodb://127.0.0.1:27017/?directConnection=true&serverSelectionTimeoutMS=2000&appName=mongosh+1.6.0
C:\>mongosh "mongodb://[::1]:27017" --quiet --eval "db.getMongo()"
mongodb://[::1]:27017/?directConnection=true&appName=mongosh+1.6.0
If you don't run MongoDB as a service then it would be
mongod --bind_ip_all --ipv6 <other options>
NB, I don't like configuration
net:
bindIp: <ip_address>
in my opinion this makes only sense on a computer with multiple network interfaces. Use bindIp: localhost if you need to prevent any connections from remote computer (e.g. while maintenance or when used as backend database for a web-service), otherwise use bindIpAll: true

React eCommerce app not able to fetch data from backend, throwing error 400 on the debugger

Creating a React eCommerce app, deployed on Firebase and Payment gateaway is integrated with stripe.
As soon as I place an order, I am supposed to push it to the backend, and again fetch it back to the front end to show the order details to the user.
This is the code in "Index.js" in "Functions" folder, which serves the API call:
const express = require('express');
const cors = require('cors');
const stripe = require("stripe")
("XXXXXXXX");
// API
// - App Config
const app = express();
// - Middlewears
app.use(cors({ origin: true }))
app.use(express.json());
// - API routes
app.get("/", (request, response) => response.status(200).send('hello world'))
app.post("/payments/create", async (request, response) => {
const total = request.query.total;
console.log("Payment Request Revieved for this amount ->", total)
const paymentIntent = await stripe.paymentIntents.create({
amount: total, // subunits of currency
currency: "usd",
});
// 201 - OK - Created Something
response.status(201).send({
clientSecret: paymentIntent.client_secret
});
})
// - Listen Command
exports.api = functions.https.onRequest(app)
These are the errors I'm getting in the browser debugger
It looks like you're using the development build of the Firebase JS SDK.
When deploying Firebase apps to production, it is advisable to only import
the individual SDK components you intend to use.
For the module builds, these are available in the following manner
(replace <PACKAGE> with the name of a component - i.e. auth, database, etc):
CommonJS Modules:
const firebase = require('firebase/app');
require('firebase/<PACKAGE>');
ES Modules:
import firebase from 'firebase/app';
import 'firebase/<PACKAGE>';
Typescript:
import firebase from 'firebase/app';
import 'firebase/<PACKAGE>';
./node_modules/firebase/dist/index.esm.js # index.ts:18
This:
v3:1 You may test your Stripe.js integration over HTTP. However, live Stripe.js integrations must use HTTPS.
Also this:
Failed to load resource: the server responded with a status of 400 ()
And these errors are showing in my VS code terminal:
(node:1700) UnhandledPromiseRejectionWarning: Error: This value must be greater than or equal to 1.
> at Function.generate (D:\WebDev\TutorialProjects\React\AmazonClone\amazon-clone\functions\node_modules\stripe\lib\Error.js:40:16)
> at IncomingMessage.<anonymous> (D:\WebDev\TutorialProjects\React\AmazonClone\amazon-clone\functions\node_modules\stripe\lib\StripeResource.js:203:33)
> at Object.onceWrapper (events.js:421:28)
> at IncomingMessage.emit (events.js:327:22)
> at endReadableNT (internal/streams/readable.js:1327:12)
> at processTicksAndRejections (internal/process/task_queues.js:80:21)
> (Use `node --trace-warnings ...` to show where the warning was created)
> (node:1700) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
> (node:1700) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
It sounds like you're not setting amount correctly, but you're suppressing the details of the Stripe API error response, which would make this more obvious. You should add some debug logging in your /payments/create handler. Check your Dashboard logs to see the full error details another way.
What is the request shape that your client app makes to your back end on that endpoint? You're using express.json() as though you expect some json-encoded POST body, but then your handler is looking at query parameters with request.query.total. Have you checked whether you're getting the expected value here?
You need to send an amount that is both >=1 and at least the minimum charge for your currency.

How to solve Mongoose v5.11.0 model.find() error: Operation `products.find()` buffering timed out after 10000ms"

How to solve model.find() function produces "buffering timed out after ... ms"? I'm using mongoose v 5.11.0, npm v6.14.8 and mongodb v
Here's the code.
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
const assert = require('assert');
var mongoose = require('mongoose');
try {
var db = mongoose.connect('mongodb://localhost:27017', {useNewUrlParser: true, dbName: 'swag-shop' });
console.log('success connection');
}
catch (error) {
console.log('Error connection: ' + error);
}
var Product = require('./model/product');
var WishList = require('./model/wishlist');
//Allow all requests from all domains & localhost
app.all('/*', function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With, Content-Type, Accept");
res.header("Access-Control-Allow-Methods", "POST, GET");
next();
});
app.get('/product', function(request, response) {
Product.find({},function(err, products) {
if (err) {
response.status(500).send({error: "Could not fetch products. "+ err});
} else {
response.send(products);
}
});
});
app.listen(3004, function() {
console.log("Swag Shop API running on port 3004...");
});
The product model:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var product = new Schema({
title: String,
price: Number,
likes: {type: Number, default: 0}
});
module.exports = mongoose.model('Product', product);
Additionally, running the file also produces the following warnings:
D:\Test\swag-shop-api>nodemon server.js
[nodemon] 2.0.6
[nodemon] to restart at any time, enter `rs`
[nodemon] watching path(s): *.*
[nodemon] watching extensions: js,mjs,json
[nodemon] starting `node server.js`
success connection
Swag Shop API running on port 3004...
(node:28596) UnhandledPromiseRejectionWarning: TypeError [ERR_INVALID_ARG_TYPE]: The "url" argument must be of type string. Received type function ([Function (anonymous)])
at validateString (internal/validators.js:122:11)
at Url.parse (url.js:159:3)
at Object.urlParse [as parse] (url.js:154:13)
at module.exports (D:\Test\swag-shop-api\node_modules\mongoose\node_modules\mongodb\lib\url_parser.js:15:23)
at connect (D:\Test\swag-shop-api\node_modules\mongoose\node_modules\mongodb\lib\mongo_client.js:403:16)
at D:\Test\swag-shop-api\node_modules\mongoose\node_modules\mongodb\lib\mongo_client.js:217:7
at new Promise (<anonymous>)
at MongoClient.connect (D:\Test\swag-shop-api\node_modules\mongoose\node_modules\mongodb\lib\mongo_client.js:213:12)
at D:\Test\swag-shop-api\node_modules\mongoose\lib\connection.js:820:12
at new Promise (<anonymous>)
at NativeConnection.Connection.openUri (D:\Test\swag-shop-api\node_modules\mongoose\lib\connection.js:817:19)
at D:\Test\swag-shop-api\node_modules\mongoose\lib\index.js:345:10
at D:\Test\swag-shop-api\node_modules\mongoose\lib\helpers\promiseOrCallback.js:31:5
at new Promise (<anonymous>)
at promiseOrCallback (D:\Test\swag-shop-api\node_modules\mongoose\lib\helpers\promiseOrCallback.js:30:10)
at Mongoose._promiseOrCallback (D:\Test\swag-shop-api\node_modules\mongoose\lib\index.js:1135:10)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:28596) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:28596) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
I tried increasing the bufferTimeoutMS or disabling the bufferCommands but still it won't work.
According to Documentation found in this link: https://mongoosejs.com/docs/connections.html#buffering
Mongoose lets you start using your models immediately, without waiting for mongoose to establish a connection to MongoDB.
That's because mongoose buffers model function calls internally. This
buffering is convenient, but also a common source of confusion.
Mongoose will not throw any errors by default if you use a model
without connecting.
TL;DR:
Your model is being called before the connection is established. You need to use async/await with connect() or createConnection(); or use .then(), as these functions return promises now from Mongoose 5.
The issue on model.find() error: Operation products.find() buffering timed out after 10000ms" was resolved by removing the node_module folder, *.json files and reinstalling the mongoose module.
The issue on the warnings was resolved by following this instructions https://mongoosejs.com/docs/deprecations.html
Well, I encountered the same problem and had very similar code. I got the same error when sending a get request while testing.
Eventually, I found the solution that my localhost DB wasn't running at that moment. Though it's a foolish error, but I had a hard time finding it.
This error poped becuase you are trying to access models before creating the connection with the database
Always link your mongodbconnection file (if you have created) in app.js by
var mongoose = require('./mongoconnection');
or just keep mongodb connection code in app.js
For me was 100% MongoDB Atlas issue.
I've created a cluster in Sao Paulo that for some reason wasn't working as expected. I've deleted it, create a new one in AWS / N. Virginia (us-east-1) and everything started working again.
i'm using this function to connect to the db and avoid some warnings
mongoose.connect(
url,
{ useNewUrlParser: true, useUnifiedTopology: true },
function (err, res) {
try {
console.log('Connected to Database');
} catch (err) {
throw err;
}
});
just use 127.0.0.1 instead of localhost
mongoose.connect('mongodb://127.0.0.1:27017/myapp');
Or use family:4 in mongoose.connect method like that
mongoose.connect('mongodb://localhost:27017/TESTdb', {
family:4
})
.then(() => {
console.log('FINE');
})
.catch(() => {
console.log("BAD");
})
I had the same problem.
After a long search I was able to find it.
I created a new user in MongoDB atlas settings. I changed the MongoDB connection value with the new user.
Changing DNS setting to 8.8.8.8 or changing mongodb connection settings to 2.2.12 did not work.
In my case my i forgot to import db.config file in server.js file
There has been a change in mongoose v5^ the spaghetti code has been refactored, It now returns a promise that resolves to the mongoose singleton. so you don't have to do this.
// You don't have todo this
mongoose.connect('mongodb://localhost:27017/test').connection.
on('error', handleErr).
model('Test', new Schema({ name: String }));
// You can now do this instead
mongoose.connect('mongodb://localhost:27017/test').catch(err);
Check here for references
What's new in Mongoose v5^
If this doesn't work for you, you can then change your connection URL > Select your driver and version to v2.2.12 or later
First you should check in which port mongodb currently running.
Use this command to check that port
sudo lsof -iTCP -sTCP:LISTEN | grep mongo
If there you find different port rather than 27017, you should change it
I was having this issue only on deployed lambda functions and everything worked fine on my local. The following worked for me.
Delete node_modules folder.
npm install
commit/push the new package-lock.json file
merge / run cicd pipeline / deploy.
For me, the issue was node version. I was getting the same error with nodejs version 17.
After trying all the suggestions on this thread, stumbled upon this open issue. Tried downgrading node, but that did not work, finally uninstalled node 17 completely and installed node 16 and the problem was solved!
You can check your node version on Mac using node --version
This means that, mongo connection has not been established like others have mentioned, go through your code and see if perhaps you forgot to create a mongoConnect() function to connect with your atlas URI
the best way is to put your initialization in a function, connect to db before starting the server. use a combination of async and a condition to check if environment variables are there(incase db url is in env) here is a sample code.
const start = async () => {
if (!process.env.DB_URI) {
throw new Error('auth DB_URI must be defined');
}
try {
await mongoose.connect(process.env.DB_URI!, {
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true,
});
console.log('Server connected to MongoDb!');
} catch (err) {
throw new DbConnectionError();
console.error(err);
}
const PORT = process.env.SERVER_PORT;
app.listen(PORT, () => {
console.log(`Server is listening on ${PORT}!!!!!!!!!`);
});
};
start();
You should check if string connection is correct, because in my case I forgot to include the .env file in my proyect. This file contains string connection for my server in digital ocean.
MONGO_URI="mongodb+srv://server:gfhyhfyh.mongo.ondigitalocean.com/db_customers"

MongoDB (Mongoose) with Node.js connection errors - Looking for insight

I am new to node.js and mongoDB Atlas. I am having an issue connecting to Mongo Atlas using the Node.js version 3.0 or later connection string.
const MongoDB = 'mongodb+srv://<user>:<password>#cluster0-nnezr.mongodb.net/<dbname>?retryWrites=true&w=majority'
When I use this connection string I get the following error -
MongoDB connection error: Error: querySrv ETIMEOUT _mongodb._tcp.cluster0-nnezr.mongodb.net
at QueryReqWrap.onresolve [as oncomplete] (dns.js:203:19) {
errno: undefined,
code: 'ETIMEOUT',
syscall: 'querySrv',
hostname: '_mongodb._tcp.cluster0-nnezr.mongodb.net'
}
(node:38809) UnhandledPromiseRejectionWarning: Error: querySrv ETIMEOUT _mongodb._tcp.cluster0-nnezr.mongodb.net
at QueryReqWrap.onresolve [as oncomplete] (dns.js:203:19)
(Use node --trace-warnings ... to show where the warning was created)
(node:38809) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside ofan async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag --unhandled-rejections=strict (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:38809) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections thatare not handled will terminate the Node.js process with a non-zero exit code.
I have found a workaround using the previous connection string for node.js version 2.2.12 -
mongodb://<user>:<password>#cluster0-shard-00-00-nnezr.mongodb.net:27017,cluster0-shard-00-01-nnezr.mongodb.net:27017,cluster0-shard-00-02-nnezr.mongodb.net:27017/<dbname>?ssl=true&replicaSet=Cluster0-shard-0&authSource=admin&retryWrites=true&w=majority
When connecting I have to add {useUnifiedTopology: true}
mongoose.connect(mongoDB, { useNewUrlParser: true, useUnifiedTopology: true });
Can anyone give me a little insight on what im doing wrong with the new connection string?
Thanks!
have write user, password and maybe also database ,
const MongoDB = 'mongodb+srv://<user>:<password>#cluster0-nnezr.mongodb.net/<dbname>?retryWrites=true&w=majority'
user = your mongodb user name
password = your mongodb password
dbname = Database name
and don't forget to create a new user in MongoDB atlas.

How do I properly set up the Cassandra client in Javascript?

Right now, I'm running a docker with Cassandra on it. I have a javascript file that sits outside the docker that needs to connect to Cassandra. I've found a node package that interfaces w/ JS, called cassandra-driver. However, with the following code:
var cassandra = require('cassandra-driver');
var PlainTextAuthProvider = cassandra.auth.PlainTextAuthProvider;
const client = new cassandra.Client({
contactPoints: ['127.0.0.1:9042'],
localDataCenter: '127.0.0.1',
keyspace: 'wasabi_experiments',
authProvider: new PlainTextAuthProvider('cassandra', 'cassandra')
});
I get
(node:17836) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): NoHostAvailableError: All host(s) tried for query failed. First host tried, 127.0.0.1:9042: ArgumentError: localDataCenter was configured as '127.0.0.1', but only found hosts in data centers: [datacenter1]. See innerErrors.
(node:17836) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 2): NoHostAvailableError: All host(s) tried for query failed. First host tried, 127.0.0.1:9042: ArgumentError: localDataCenter was configured as '127.0.0.1', but only found hosts in data centers: [datacenter1]. See innerErrors.
How can I get this to work?
Your problem is that you're using the 127.0.0.1 as value for localDataCenter parameter, but it should be set not to the address of the machine, but to the name of the Cassandra data center - in your case this is datacenter1. Change the value of that parameter to datacenter1, and it will start to work.
It would be:
const { Client, auth } = require('cassandra-driver');
const client = new cassandra.Client({
contactPoints: ['127.0.0.1:9042'],
localDataCenter: 'datacenter1', // here is the change required
keyspace: 'wasabi_experiments',
authProvider: new auth.PlainTextAuthProvider('cassandra', 'cassandra')
});
client.connect();
P.S. I recommend to read documentation for Node.js driver, and also "Developing applications with DataStax drivers" guide.
try first with a Cassandra client, ensure Cassandra is working properly and you can access it. After that try with the code.
Also you can try to access the 127.0.0.1:9042 using telnet or netcat to see if the port is open and listening. You can use netstat too for this task.

Categories

Resources