I am trying to connect to a MongoDB database.I have followed all the steps here https://youtu.be/EcJERV3IiLM but am getting an error.
The index.js file looks like this,
const dotenv = require('dotenv')
dotenv.config()
const mongodb = require('mongodb')
mongodb.connect(process.env.CONNECTIONSTRING, async function(err,client){
const db = client.db()
const results = await db.collection("student").find().toArray()
console.log(results)
The error I get is,
mongodb.connect is not a function
So it seems to be reading as far line 5:9 which is mongodb.connect in index.js and just stops.
I put this file index.js beside the .env file and beside that .gitignore which contains the the .env file. The .env file has the code which I copied from the Mongodb AtlSAS Cloud Service.
I also created a user and and autogenerated and saved a password. Both of which I placed in the string. And I put in the string the name of the database name "blah" The table/document is called "student". That's in the index.js code above. So the database name and the document name are blah.student.
I documented what I tried here, http://www.shanegibney.com/shanegibney/mongodb-setup/
The tutorial video is here, https://youtu.be/EcJERV3IiLM
I am on Ubuntu Linux.
I am currently running index.js in the terminal in a directory called mongostack, with
node index.js
but should I use,
nodemon index.js
And for this should I install nodemon and how do I do that?
Do I need to download it first and if so where do I get it?
I think you need to get MongoClient. Try changing:
const mongodb = require('mongodb')
to:
const mongodb = require('mongodb').MongoClient;
You have to create a MongoClient see https://www.mongodb.com/docs/drivers/node/current/quick-start/
const { MongoClient } = require("mongodb");
const uri = process.env.CONNECTIONSTRING;
const client = new MongoClient(uri);
async function run() {
await client.connect();
const db = client.db("yourdb")
const results = await db.collection("student").find().toArray()
console.log(results)
}
run();
Related
const jsonServer = require('json-server')
const cors = require('cors')
const path = require('path')
const server = jsonServer.create()
const router = jsonServer.router(path.join(__dirname, 'db.json'))
const middlewares = jsonServer.defaults()
server.use(cors())
server.use(jsonServer.bodyParser)
server.use(middlewares)
server.use(router)
const PORT = 8000
server.listen(PORT, () => {
console.log(`JSON Server is running on http://localhost:${PORT}`)
})
I am using cyclic.sh for deployment. How to solve this error?
I was trying to deploy a json-server. And while doing a post request I got this error.
Taking as a starting point that you shouldn't use a tool like json-server in production environments, I could understand you might be using it for demo purposes. That case, there are some serverless solutions which prevents your code from open files in write mode, so that's why the jsonServer.router(...) line fails its execution.
If you don't matter about that db.json file being updated by the requests (because anyway, your deployment solution doesn't seem to allow it), you could just use instead a js object, that can be modified in memory (but, of course, the json file will still keep intact). So, instead of:
const router = jsonServer.router(path.join(__dirname, 'db.json'))
try using something like:
const fs = require('fs')
const db = JSON.parse(fs.readFileSync(path.join(__dirname, 'db.json')))
const router = jsonServer.router(db)
I've read some code that uses the dotenv package to create configurations.
When I read a file that contains PostgreSQL code for Pool, the code looks like this:
const pg = require('pg')
const { Pool } = pg
// This pool was created without completing the pool connection configuration.
const pool = new Pool()
However, I see that this pool configuration is written in the.env file.
#POOL CONFIGURATIONS
PGUSER=username
PGPASSWORD=password
PGHOST=localhost
PGDATABASE=databasename
PGPORT=5432
and .env file is called once in main file :
// main file
require('dotenv').config()
const express = require('express')
// below is the server
Why is a pool created without passing any configuration objects as arguments?
How does it work in the background?
I still can't figure this out clearly.
I've tried searching for this behavior, but I haven't found it yet.
When you run
require('dotenv').config()
that sets everything in your .env file to be on process.env.*.
For example, you say PGUSER=username, so now process.env.PGUSER === "username"
pg.Pool seems to go with those environment variables by default
In a Mongo shell script I need to read a file to delete documents by _id but I can't import the FileReader library.
I launch script from bash to do simple find() and it works:
mongosh --host xxx --port 27017 --username xxx --password xxx --eval "var country='$country';var file='$inputDataFile'" --file scriptFile.js
But whenever I try to import a library in the js it shows the error:
TypeError: Cannot assign to read only property 'message' of object 'SyntaxError:
'import' and 'export' may appear only with 'sourceType
The same js file I call from nodejs and the import is correct.
Right now I do the deletion of _ids contained in a file using nodejs. I would like to find a way to use Mongo shell script for all my queries
I managed to solve my problem with the help of Include External Files and Modules in Scripts
Create package.json in the same directory as your js
Add the necessary libraries to package.json
Install libraries
Use require to import it
Code
var fs = require('fs');
console.log(country)
console.log(file)
db = db.getSiblingDB('mongotest')
const allFileContents = fs.readFileSync(file, 'utf-8');
var lines = allFileContents.split("\r")
for (var i = 0; i < lines.length; i++) {
const user = JSON.parse(lines[i]);
var userId = user._id
if (!(userId instanceof ObjectId)) {
userId = new ObjectId(userId);
}
db.userChat.deleteOne({ _id: userId })
}
Thanks for your help
I'm a MERN stack beginner. I came across this snippet of code from a basic CRUD and I know that it works, but I don't get how.
//in server.js
const database = require('./database');
//in database.js
const mongoose = require('mongoose'); //importing mongoose
mongoose.connect('mongodb://localhost/monguse', {useNewUrlParser:true}) //connected to db
.then((db)=>{console.log('Database connected')}) //message if ok
.catch((err) =>{console.log(`Database connection error: ${err}`)}); //catching errors
module.exports = mongoose;
I understand what is going on in database.js (It is my own version), but why does it work without using any method in server.js? It appears to make the connection only from using the "require" function. then in my routes there is no mention of that again; just using mongoose models in the requests.
Thanks!
In database.js you create an instance of the database and export it by name mongoose, and in server.js you are importing that instance of the mongoDB by name database.
Hello i am new in Nodejs & MongoDb.
I created controllers for API where i want create new items in MongoDB, edit, search items.
Now i am connecting to MongoDB via mongoose in main file server.js.
But i need that i can create, edit in editor.js.
I tried to export mongoose module, but it was unsuccessfull.
How i can do this in right way?
my structure
`editor.js` file - where i want have access to database
const models = require('./../models');
const client = require('./../../server');
const mongoose = require('mongoose');
let db;
// const db = client.db('todo');
module.exports = {
getNewsById: async (req, res) => {
console.log(req.params);
// console.log(req);
res.send({oK: 'ok'});
},
createNews: async (req, res) => {
const newItem = req.body;
newItem['publishedAt'] = Date.now();
console.log('HERE', client);
console.log('HERE2', client.db.collection('test').insertOne({
item: 'canvas',
qty: 100,
tags: ['cotton'],
size: { h: 28, w: 35.5, uom: 'cm' }
}));
}
}
In editor.js after importing mongoose, you can simply load your model using -
const db = require('mongoose');
const testModel = db.model('test');
And then you can call your db queries similar to -
testModel.insert(...);
testModel.find();
Once you have built your model using mongoose, it is available in the application. You just need to get it through mongoose.
If you need more help, you can refer to my sample project at https://github.com/kravigupta/nodejs-express-mongo-auth
For every new developer who is learning node.js, the first thing they go with the MongoDB connection with the node.js.
I will suggest you keep the MongoDB connection URL, username and password in a separate file say it db.config.js file and then import that file into you server.js or app.js or main file of your node.js and then connect mongo with the try catch block to handle the error. IF you need to learn in more details then you can refer to this link.