MongoDB won't insert document - node.js

I don't know what I am doing wrong, however the following is not working.
I have the database connecting however when I try and use the connection it won't let me.
index.js
config = require('./config');
const express = require('express');
const app = express();
const mDB = require('./components/mongodb').connect(config.dbUri);
app.get('/testDB', (req,res) =>{
const user = { name: 'John', age: 30 };
mDB.insertOne(user, (error, result) => {
if (error) {
console.log(error);
return;
}
console.log(`Successfully inserted user: ${result.insertedId}`);
res.send("inserted");
});
});
app.listen(3000, () => {
console.log('App listening on port 3000');
});
./components/mongodb.js
const MongoClient = require('mongodb').MongoClient;
module.exports.connect = (uri) => {
MongoClient.connect(uri, { useNewUrlParser: true }, (err, client) => {
if (err) {
console.error(`MongoDB connection error: ${err}`);
process.exit(1);
}
console.log('Successfully connected to MongoDB');
module.exports.client = client;
});
};
module.exports.insertOne = (collection, document) => {
module.exports.client.db('PodToo').collection(collection).insertOne(document, (error, result) => {
if (error) {
console.log(error);
return;
}
console.log(`Successfully inserted document: ${result.insertedId}`);
});
};
I get the Successfully connected to MongoDB
But then when I try and use it I am receiving
TypeError: Cannot read properties of undefined (reading 'insertOne')

In the danger of stating the obvious: You are missing the first argument to your insertOne function, the collection name.
Did you mean
mDB.insertOne('users', user, ...
?

Related

client.get("ping", (err, data) => in redis hangs my node js code

This is my server call to route
const redis = require("redis");
const client = redis.createClient();
client.connect();
module.exports = client;
This is my API route
app.get("/api/ping", middleWare.cacheRouteOne, RouteController.routeOne);
This is my cache route function
exports.cacheRouteOne = (req, res, next) => {
client.get("ping", (err, data) => {
console.log(data);//To check whether is working or not.
if (err) throw err;
if (data != null) {
res.json({
postss: JSON.parse(data),
});
} else {
next();
}
});
};
And this is my API call code
exports.routeOne = (req, res) => {
axios
.get("some APi CALL")
.then((response) => {
client.setEx("ping", 3600, JSON.stringify(response.data.posts));
console.log(client);
res.status(200).json({
status: true,
posts: response.data.posts,
});
});
};
When it calls the middle function it hangs my code after clinet.get()
I got the answer, I was making a call back but for forget to add await ,
so this is the updated middleware code
exports.cacheRouteOne = async (req, res, next) => {
let data = await client.get("ping");
console.log("data of ping");
if (data != null) {
res.json({
postss: JSON.parse(data),
});
console.log("yes");
} else {
next();
}
};
use this code to connect redis
const client = redis.createClient({
socket: {
port: 6379,
host: "127.0.0.1",
}
});
(async () => {
// Connect to redis server
await client.connect();
})();
console.log("Attempting to connect to redis");
client.on('connect', () => {
console.log('Connected!');
});
// Log any error that may occur to the console
client.on("error", (err) => {
console.log(`Error:${err}`);
});

db.collection is not a function when nodejs connect to mongodb via MongoDB native NodeJS driver

I'm trying to connect to mongoDB via mongodb native nodejs driver, but I'm having a problem.
conn.js
'use strict'
const { MongoClient } = require('mongodb');
const url = 'mongodb://localhost:27017/test';
const dbname = 'test';
const dbConnect = () => {
return new Promise((resolve, reject) => {
MongoClient.connect(url, { useNewUrlParser: true }, (err, client) => {
if (err) {
reject(err);
} else {
resolve(client.db(dbname));
}
});
});
}
module.exports = {
dbConnect
}
user.js
const conn = require('../conn');
router
.post('/', async (ctx, next) => {
try {
let user = await conn.dbConnect.collection('user').findOne({email: email});
console(user);
} catch (e) {
ctx.body = {error:true, msg: e instanceof Error ? e.message : e};
}
})
module.exports = router;
But I got the error db.collection is not a function, why? Thank you.

Node + Express: How to retrieve data from MongoDB via Azure

I am a frontend developer. A colleague has kindly built me a MongoDB/Cosmos database in Azure and allowed me to retrieve a single record into my frontend. He has since gone on holiday with no cover.
(I am confused what type of database it is, since it says Azure Cosmos DB in Azure portal, but all the code in my server.js file refers to a MongoDB.) Server.js:
const express = require('express');
const app = express();
const url = 'mongodb://blah.azure.com';
app.use(express.static('static'));
const mongoClient = require('mongodb').MongoClient
let db;
app.listen(process.env.PORT || 3000, async () => {
console.log('App listening on port 3000!')
const connect = await mongoClient.connect(url)
db = connect.db('ideas');
});
app.get('/api/ideas/:name', async (req, res) => {
return res.json(await db.collection('container1').findOne({key: req.params.name}));
});
I want to retrieve all documents in this database. They each have an ID. But my colleague seems to have defined an API by name. From the MongoDB docs I can use the command find({}) instead of findOne({key: req.params.name}) to return all records, but this does not work (i.e. I get no output to the console). I presume this is because of the '/api/ideas/:name'.
I have also tried:
db.open(function(err, db){
var collection = db.collection("container1");
collection.find().toArray(function(err2, docs){
console.log('retrieved:');
console.log(docs);
})
})
but i get an error that tells me I can't retrieve the property "open" of undefined.
Can anyone help me either: (1) work out how to change the API in Azure, or (2) rewrite this code to retrieve all records? I will also need to edit and insert records. Thanks
If you want to retrive data from Mongo DB in nodejs espresso application, I suggest you use the package mongoose.
For example
Create mongo.js file to add connection details
const mongoose = require('mongoose');
mongoose.Promise = global.Promise;
const accountName= 'testmongo05',
const databaseName= 'test',
const key= encodeURIComponent(''),
const port: 10255
const mongoUri = `mongodb://${env.accountName}:${key}#${accountName}.documents.azure.com:${port}/${databaseName}?ssl=true`;
function connect() {
mongoose.set('debug', true);
return mongoose.connect(mongoUri, {
useFindAndModify : false,
useCreateIndex: true,
useNewUrlParser: true,
useUnifiedTopology: true
});
}
module.exports = {
connect,
mongoose
};
Define models
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const userSchema = new Schema(
{
userId: {
type: String,
required: true,
unique: true
},
name: String,
saying: String
},
{
collection: 'Users'
}
);
const User = mongoose.model('User', userSchema);
module.exports = User;
CURD operations
const express = require('express');
const bodyParser = require('body-parser');
const User = require('./module/user');
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
require('./mongo').connect().catch(error => console.log(error));
//list users
app.get('api/users', async (req, res) => {
const docquery = User.find({});
await docquery
.exec()
.then(users => {
res.status(200).json(users);
})
.catch(error => {
res.status(500).send(error);
});
});
// get user by userId
app.get('/api/user/:uid', async (req, res) => {
const docquery =User.findOne({userId:req.params.uid })
await docquery
.exec()
.then(user => {
if (!checkFound(res, user)) return;
res.status(200).json(user);
})
.catch(error => {
res.status(500).send(error);
});
});
// create
app.post('/api/user', async (req, res) => {
const originalUser= { userId: req.body.userId, name: req.body.name, saying: req.body.saying };
const user = new User(originalUser);
await user.save(error => {
if (checkServerError(res, error)) return;
res.status(201).json('User created successfully!');
console.log('User created successfully!');
});
});
//update user by userId
app.put('/api/user/:uid', async (req, res) => {
const docquery =User.findOneAndUpdate({userId: req.params.uid}, req.body)
await docquery.exec()
.then((user) =>{
if (!checkFound(res, user)) return;
res.status(200).json("User update successfully");
console.log('User update successfully!');
})
.catch(error =>{
res.status(500).send(error);
})
});
//delete user by userId
app.delete('/api/user/:uid', async (req, res) => {
const docquery = User.findOneAndRemove({userId: req.params.uid })
await docquery.exec()
.then(user =>{
if (!checkFound(res, user)) return;
res.status(200).json("user deleted successfully!");
console.log('user deleted successfully!');
})
.catch(error =>{
res.status(500).send(error);
})
});
function checkServerError(res, error) {
if (error) {
res.status(500).send(error);
return error;
}
}
function checkFound(res, user) {
if (!user) {
res.status(404).send('user not found.');
return;
}
return user;
}
Test
a. Create user
b. get user
c. List Users
d. Update User
e delete user

Problems returning database information with MongoDB, Node.js and Express

const express = require('express');
const second = express();
const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');
const url = 'mongodb://localhost:27017';
// Database Name
const dbName = 'myorders';
// Use connect method to connect to the server
MongoClient.connect(url, function(err, client) {
assert.equal(null, err);
console.log("The connection was awesome");
const db = client.db(dbName);
second.get('/Students',(req,res) => {
const findStudents = function(db,call) {
const collection = db.collection('Students');
collection.find({}).toArray(function (err,result) {
if (!err) {
res.send(result)
} else {
console.log(err);
call(err);
}
});
}
});
client.close();
});
second.listen(3200,() => {
console.log('We got it running');
});
module.exports = second;
So I am trying to display my mongodb information on a web server and here are the screen shots
Above is the MongoDB collection of students and marks
And above is my Node.js command prompt and I get a deprecation warning. Is there any way I can fix it? Is there any other error why I can't display the information in the web server?
To fix this deprecation warning, all you need is to do what it says: pass the option useNewUrlParse: true in the options object to MongoClient.connect. So the line where you connect to MongoDB database would be:
MongoClient.connect(url, { useNewUrlParse: true }, function(err, client)
Anyway, this is just a warning, not a blocking error, and your app is running. I think there are several things wrong in your code, mainly that you declare the function to be executed on the GET to /Students within the callback of the connection to the database and that you close that connection so that the data could no longer be accessed. I think this code should work for you:
const express = require('express');
const second = express();
const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');
const dbUrl = 'mongodb://localhost:27017';
const dbName = 'myorders';
let db;
MongoClient.connect(url, (err, client) => {
assert.equal(null, err);
db = client.db(dbName);
console.log("The connection was awesome");
});
second.listen(3200, () => {
console.log('We got it running');
});
second.get('/Students', (req, res) => {
db.collection('Students').find().toArray((err,result) => {
if (!err) {
res.send(result)
} else {
console.log(err);
res.status(500).send(err);
}
});
});
EDIT:
If you think that the database should not be always opened, yous should connect and close at each request to /Students, this way:
second.listen(3200, () => {
console.log('We got it running');
});
second.get('/Students', (req, res) => {
MongoClient.connect(url, (err, client) => {
if (err) return res.status(500).send(err);
db = client.db(dbName);
db.collection('Students').find().toArray((err,result) => {
if (!err) {
res.send(result)
} else {
console.log(err);
res.status(500).send(err);
}
client.close();
});
});
});

Node/express postgresql stored procedure / function

I want to call a stored procedure / function in postgresql from node/express. I am using Angular 5.
Installed packages:
express: 4.16.2,
pg: ^7.4.0
Other required packages are also installed
Below is the code of my API - I want to replace all queries with my stored procedure / function call
const express = require('express');
const router=express.Router();
const {Pool,Client} = require('pg');
const connectionString = 'postgresql://postgres:1#localhost:5432/dbAngular'
// const client = new Client({
// connectionString:connectionString
// })
router.get('/employees', (err, res, done) => {
const client = new Pool({
connectionString:connectionString
})
client.connect((err)=>{
if(err!=undefined)
{
console.log('connection not established message as follow '+err.message+'')
}
});
client.query('select * from getEmployees();', (err, result) => {
if (err) {
console.log(err.stack) ;
client.end();
} else {
client.end();
console.log(result.rows);
res.json(result.rows);
}
})
})
//SAVE
router.post('/employees', (req, res,next) => {
const client = new Pool({
connectionString:connectionString
})
console.log( req.body);
var employee=req.body;
const query = {
text: 'INSERT INTO employes(name) VALUES($1)',
values: [employee.name]
}
client.connect((err)=>{
if(err!=undefined)
{
console.log('connection not established '+err.message+'')
}
});
client.query(query, (err, result) => {
if (err) {
console.log('ERRROOORRRRR');
client.end();
console.log(err.stack)
} else {
console.log('SAVEEEEE');
client.end();
// console.log(res.rows[0])
res.json();
}
})
});
//delete
router.delete('/employees/:id', (req, res,next) => {
const client = new Pool({
connectionString:connectionString
});
console.log('id passed is ' + req.param.id);
client.query('DELETE FROM employes WHERE empid=($1)',[req.param.id], (err, result) => {
if (err) {
console.log('ERRROOORRRRR');
client.end();
console.log(err.stack)
} else {
console.log('SAVEEEEE');
client.end();
// console.log(res.rows[0])
res.json();
}
});
});
module.exports=router;

Resources