I'm having trouble capturing the current collection in mongodb.
I have a file with FetchUsers function which returns a collection with users:
const mongoose = require('mongoose');
const uri = "mongodb+srv://<username>:<password>#<cluster-url>.sdzp0ug.mongodb.net/?
retryWrites=true&w=majority";
const fetchUsers= () => {
const connectionParams = {
useNewUrlParser: true,
useUnifiedTopology: true,
}
try{
mongoose.connect(uri);
} catch (error)
{
console.log(error);
}
const collectionName = 'UsersTests'
const Users = mongoose.model(collectionName, new mongoose.Schema({}));
Users .find({}, function(err, docs) {
if (err) {
console.error(err);
return;
}
console.log(`Documents in ${collectionName}:`);
mongoose.connection.close();
console.log(`My current collection: ${docs}`);
return docs;
});
}
module.exports = fetchUsers
In another file I have a function that takes the returned value and then displays it:
const fetchData = require("../../controllers/USersControllers/fetchUsers.js");
async function displayUsers() {
let users = await fetchData();
console.log(users);
}
module.exports = displayUsers;
and all this is running on the express server
const express = require("express");
const displayUsers = require("./public/js/displayUsers.js");
const app = express();
app.use(express.static("public"));
app.use(express.urlencoded({ extended: true }));
app.listen(5000, () => {
console.log("Server started on port 3000");
displayUsers();
});
The problem is that displayUsers displays undefined and doesn't wait until fetchData returns a collection.
OK, I corrected the code and it works.
GetUsersModel.js:
const mongoose = require("mongoose");
const uri =
"mongodb+srv://<username>:<password>#<cluster-url>.sdzp0ug.mongodb.net/?
retryWrites=true&w=majority";
const connectionParams = {
useNewUrlParser: true,
useUnifiedTopology: true,
};
try {
mongoose.connect(
uri
);
console.log("Database conected!");
} catch (error) {
console.log(error);
console.log("Database connection failed");
}
const Schema = new mongoose.Schema({
content: String,
title: String,
author: String,
});
const Users =
mongoose.model.userTest ||
mongoose.model("userTest", Schema);
module.exports = Users;
fetchUsersData.js
const mongoose = require('mongoose');
const Users =
require("../controllers/SnippetsControllers/GetSnippetModel.js");
const uri =
"mongodb+srv://<username>:<password>#<cluster-url>.sdzp0ug.mongodb.net/?
retryWrites=true&w=majority";
const fetchUsers = () => {
const connectionParams = {
useNewUrlParser: true,
useUnifiedTopology: true,
}
try{
mongoose.connect(uri);
console.log('Database conected!!!!!')
} catch (error)
{
console.log(error);
console.log('Database connection failed')
}
return new Promise((resolve, reject) => {
Users.find({}, function(err, docs) {
if (err) {
reject(err);
} else {
resolve(docs);
}
});
});
}
module.exports = fetchUsers;
UseUsersData.js
const fetchData = require("../models/fetchUsersData");
async function displayUsers(req) {
let usersContainer = [];
try {
let users = await fetchData();
let usersArray = users;
console.log(usersArray);
} catch (error) {
console.log(error);
}
}
Related
Creating a chat server.
However, when I send a message, it goes into the queue, but then mysql doesn't have data. I think the server is turning on, but I keep getting an error like Socket closed absolutely during opening handshake Help me
consumer.js
`
Consumer: async () => {
try {
const connect = await amqp.connect(amqpURL);
const ch = await connect.createChannel();
const queue = "queue";
await ch.assertQueue(queue, async (message) => {
console.log(message.value.toString());
});
arr.push(JSON.parse(message.value.toString()));
console.log(arr);
if (arr.length == 5) {
try {
const rows = await chatting
.bulkCreate(arr, { hooks: true })
.catch((err) => {
console.log(err);
});
arr.splice(0);
console.log(rows);
return;
} catch (err) {
console.log(err);
}
ch.ack(message);
}
} catch (err) {
console.log(err);
}
},
app.js
`
const express = require("express");
const app = express();
const cors = require("cors");
const http = require("http");
const server = http.createServer(app);
const { Server } = require("socket.io");
const io = new Server(server);
const { chatting, sequelize } = require("./models");
const rabbitmq = require("./rabbit");
//const consumer = require("./consumer");
const amqp = require("amqplib");
const amqpURL = "amqp://localhost:5672";
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cors());
sequelize
.sync({ force: false })
.then(() => {
console.log("연결됨");
})
.catch((err) => {
console.log(err);
});
const send = async (message) => {
try {
console.log(message);
const connect = await amqp.connect(amqpURL);
const channel = await connect.createChannel();
const exchange = "exchange";
const queue = "queue";
const routingkey = "sample.routing";
await channel
.assertExchange(exchange, "direct", { durable: true })
.catch((err) => console.log(err));
await channel.assertQueue(queue, { durable: true });
await channel.bindQueue(queue, exchange, routingkey);
await channel.publish(exchange, routingkey, Buffer.from(message));
} catch (err) {
console.log(err);
}
};
app.get("/", (req, res) => {
res.sendFile(__dirname + "/index.html");
});
app.get("/test", async (req, res) => {
try {
const { idx } = req.body;
const rows = await chatting.findOne({ idx: idx });
if (rows) return res.status(200).json({ result: rows });
} catch (err) {
console.log(err);
}
});
io.on("connection", (socket) => {
console.log("connect");
socket.on("disconnect", () => {
console.log("disconnect");
});
});
io.emit("some event", {
someProperty: "some value",
otherProperty: "other value",
});
io.on("connection", (socket) => {
socket.on("chat message", async (message) => {
try {
await send(JSON.stringify(message));
io.emit("chat message", message);
console.log(message);
} catch (err) {
console.log(err);
}
});
});
server.listen(2022, () => {
console.log("listening on :2022");
});
rabbitmq.Consumer();
`
`
pic
enter image description here
I tried many things and I want to solve
Error: Socket closed abruptly during opening handshake
at Socket.endWhileOpening
this error
This is my index.js. When I hit my API using postman, there is a bug in my getdata() method code that causes it to return the else statement rather than finding the requested resource. I'm not sure why the data targeting by ID can't be found. When I use console.log to test my code, the try statement is entered but did not find anything from the database and catch statement is returned.
const connectToMongo = require('./db');
var cors = require('cors');
const express = require('express');
const bodyParser = require('body-parser');
const photo = require('./models/photoModel');
const formidable = require('formidable');
const fs = require('fs');
const photoModel = require('./models/photoModel');
connectToMongo();
const app = express();
app.use(cors());
const port = 5000;
//app.use(express.json());
app.use(bodyParser.json());
const userData = (req, res) => {
const form = new formidable.IncomingForm();
console.log('1');
form.parse(req, (err, fields, file) => {
console.log('2');
if (fields) {
console.log('3');
const { email, mno, name } = fields;
if (!email || !mno || !name) {
console.log('4');
return res.status(400).json({
error: 'Fill all the fields',
});
}
}
if (file.photo) {
if (file.photo.size > 4000000) {
return res.status(400).json({
error: 'image size is too long',
});
}
const user = new photo(fields);
user.photo.data = fs.readFileSync(file.photo.filepath);
user.photo.contentType = file.photo.type;
user.save((err, user) => {
if (err) {
return res.status(400).json({
error: 'Not save in db',
});
}
console.log('above json');
res.json(user);
});
}
});
};
// The issue is here
const getdata = async (req, res) => {
try {
console.log('yes');
const photo = await photo.find({ photo: req.photo.id });
res.json(photo);
} catch (error) {
return res.status(400).json({
error: 'not find',
});
}
};
//router
app.post('/userdashboard', userData);
app.get('/getdata', getdata);
app.listen(port, () => {
console.log(`Dashboard Backend listening on port ${port}`);
});
This is my modelschema
const mongoose = require('mongoose');
const { Schema } = mongoose;
const PhotoSchema = new Schema({
name:{
type:String,
trim:true,
required:true
},
email:{
type:String,
trim:true,
required:true
},
photo:{
data:Buffer,
contentType:String
},
mno:{
type:Number,
required:true
}
});
module.exports=mongoose.model('photo',PhotoSchema);
First mistake you did was not adding console.error(error), if you did it would have shown exact error message.
In this case req.photo is undefined and you are trying to access id property of undefined which causes error to be thrown.
const getdata = async (req, res) => {
try {
const { photo } = req.body
// TODO: use custom error class for validation errors instead of default Error class
if (!photo) throw new Error('photo is missing')
if (!photo.id) throw new Error('photo.id is missing')
// TODO: validate photo.id is valid monogoid
const photos = await photo.find({ photo: photo.id })
res.json(photos)
} catch (error) {
console.error(error) // <-- this was missing
res.status(400).json({ error: 'not find' }) // provide good error message
return
}
}
I wrote a little of code to start learning MongoDB with Node.js in JavaScript but it doesn't work but it doesn't
give a error while running probably someone can help me with that.
The Main code:
const mongoose = require('mongoose');
const express = require('express');
const test = express();
const Blog = require('./bdSchema');
//connec to mongodb
const dbURI = 'mongodb+srv://Carsten:<int the real code the password is here>#cluster0.w6iwv.mongodb.net/tomhatesgeschaft?retryWrites=true&w=majority';
mongoose.connect(dbURI, { useNewUrlParser: true, useUnifiedTopology: true })
.then((result) => console.log("connected to db"))
.catch((err) => console.log(err))
test.get('/add-tomhatesgeschaft', (req, res) => {
const tomhatesgeschaft = new Blog({
title: 'hi'
});
tomhatesgeschaft.save()
.then((result) => {
res.send(result)
})
.catch((err) => {
console.log(err);
});
})
The BDSchema:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const BDSchema = new Schema({
title: {
type: String,
required: true,
},
});
const Blog = mongoose.model('Blog', BDSchema);
module.exports = Blog;
In your Node.js code, change the save function as below.
tomhatesgeschaft.save((err,result) => {
if (err){
console.error(err);
}
else{
res.send(result)
})
})
OR
test.get('/add-tomhatesgeschaft', async (req, res) => {
const tomhatesgeschaft = new Blog({
title: 'hi'
});
try {
await tomhatesgeschaft.save()
} catch(error) {
console.error(error)
}
})
PS: You should not use GET requests for operations such as saving data to the database. Ideally, you should use a POST request.
Example with async:
test.post('/add-tomhatesgeschaft', async (req, res) => {
const tomhatesgeschaft = new Blog({
title: 'hi'
});
try {
await tomhatesgeschaft.save()
} catch(error) {
console.error(error)
}
})
I want to make nodejs script, witch should ping host and write result in mongodb. Now I am using agenda to create a job and start a ping at the right time. How to write the result of execution to the database?
I tried to use the Mongoclient, but it seems to me that this is a little not what I need.
var ping = require('ping');
const mongo = require('mongodb');
const MongoClient = mongo.MongoClient;
const url = 'mongodb://127.0.0.1:27017/test';
const config = ['10.10.4.45']
const Agenda = require('agenda');
const dbURL = 'mongodb://127.0.0.1:27017/test';
const agenda = new Agenda({
db: {
address: dbURL,
collection: 'jobs',
options: {
useNewUrlParser: true,
useUnifiedTopology: true
}
}
});
let counter = 0;
agenda.define('Ping host 10.10.4.45', async job => {
counter++;
await console.log('Ping test #'+counter);
for(let host of config){
let res = await ping.promise.probe(host);
console.log(res.host, res.alive);
}
});
(async function() {
await agenda.start();
await agenda.every('5 seconds', 'Ping host 10.10.4.45');
})();
MongoClient.connect(url, function(err, db) {
if (err) throw err;
var dbo = db.db("test");
var myobj = [
{ name: 'John', address: 'Highway 71'}
];
dbo.collection("ping_results").insertMany(myobj, function(err, res) {
if (err) throw err;
console.log("Number of documents inserted: " + res.insertedCount);
db.close();
});
});
Save the below code in a file say ping_results.js inside your repository in a folder seeding_scripts for example and then run it using below command:
node seeding_scripts\ping_results.js
ping_results.js file.
const MongoClient = require('mongodb').MongoClient;
const DB_URI = "mongodb://localhost:27017/db_name";
const options = {
useNewUrlParser: true
};
MongoClient.connect(DB_URI, options, function (err, client) {
if (err) {
console.log("ERROR: Failed to connect to database.");
console.log(err);
return;
}
let dbName = DB_URI.split("/", -1).pop();
let collectionName = "ping_results";
let db = client.db(dbName);
console.log(`Connected to ${dbName} database successfully.`);
var data = [
{ name: 'John', address: 'Highway 71' }
];
db
.collection(collectionName)
.insertMany(data)
.then(res => {
console.log(`${res.insertedCount} Documents inserted successfully.`);
console.log("Database connection closed.");
client.close();
})
.catch(err => {
console.log(JSON.stringify(err));
console.log("Database connection closed.");
client.close();
});
});
I want to reuse MongoDB connection. I 'am aware of How to reuse mongodb connection in node.js
I want to acheive the same using Promises and Mongo driver v2
Currently I have to connect to db for every request which makes it slow. This is my code
"use strict"
var app = require('./utils/express')();
var mongodb = require('mongodb');
var MongoClient = mongodb.MongoClient;
//Actually I 'am connecting to MongoLab
var url = 'mongodb://localhost/my-mongo';
app.set('port', (process.env.PORT || 5000));
app.listen(app.get('port'), function () {
console.log('ParkMe app is running on port', app.get('port'));
});
app.get('/location/create', function(req,res,next){
MongoClient.connect(url).then(function(db) {
return db.collection('parkme_parkingLots').find({}).toArray().then(function (docs) {
return docs;
});
});
});
I want to do something like:
"use strict"
var app = require('./utils/express')();
var mongodb = require('mongodb');
var MongoClient = mongodb.MongoClient;
var url = 'mongodb://nidhind:1234#ds051635.mongolab.com:51635/my-mongo';
var db = MongoClient.connect(url).then(function(db) {
return db;
});
app.set('port', (process.env.PORT || 5000));
app.listen(app.get('port'), function () {
console.log('ParkMe app is running on port', app.get('port'));
});
app.get('/location/create', function(req,res,next){
db.collection('parkme_parkingLots').find({}).toArray().then(function (docs) {
return docs;
});
});
You're almost there, there are only a couple of changes in your code to be made:
"use strict"
var app = require('./utils/express')();
var mongodb = require('mongodb');
var MongoClient = mongodb.MongoClient;
var url = 'mongodb://nidhind:1234#ds051635.mongolab.com:51635/my-mongo';
// no need to call then() yet
var connection = MongoClient.connect(url);
app.set('port', (process.env.PORT || 5000));
app.listen(app.get('port'), function() {
console.log('ParkMe app is running on port', app.get('port'));
});
app.get('/location/create', function(req, res, next) {
// the connection is opened once, use it at will
connection.then(function(db) {
db.collection('parkme_parkingLots').find({}).toArray().then(function(docs) {
return docs;
});
});
});
Here's how I do it with contemporary syntax.
I put some comments in the code.
./db/mongodb.js
const MongoClient = require('mongodb').MongoClient
const uri = 'mongodb://user:password#localhost:27017/dbName'
let _db
const connectDB = async (callback) => {
try {
MongoClient.connect(uri, (err, db) => {
_db = db
return callback(err)
})
} catch (e) {
throw e
}
}
const getDB = () => _db
const disconnectDB = () => _db.close()
module.exports = { connectDB, getDB, disconnectDB }
./index.js
// Load MongoDB utils
const MongoDB = require('./db/mongodb')
// Load queries & mutations
const Users = require('./users')
// Improve debugging
process.on('unhandledRejection', (reason, p) => {
console.log('Unhandled Rejection at:', p, 'reason:', reason)
})
const seedUser = {
name: 'Bob Alice',
email: 'test#dev.null',
bonusSetting: true
}
// Connect to MongoDB and put server instantiation code inside
// because we start the connection first
MongoDB.connectDB(async (err) => {
if (err) throw err
// Load db & collections
const db = MongoDB.getDB()
const users = db.collection('users')
try {
// Run some sample operations
// and pass users collection into models
const newUser = await Users.createUser(users, seedUser)
const listUsers = await Users.getUsers(users)
const findUser = await Users.findUserById(users, newUser._id)
console.log('CREATE USER')
console.log(newUser)
console.log('GET ALL USERS')
console.log(listUsers)
console.log('FIND USER')
console.log(findUser)
} catch (e) {
throw e
}
const desired = true
if (desired) {
// Use disconnectDB for clean driver disconnect
MongoDB.disconnectDB()
process.exit(0)
}
// Server code anywhere above here inside connectDB()
})
./users/index.js
const ObjectID = require('mongodb').ObjectID
// Notice how the users collection is passed into the models
const createUser = async (users, user) => {
try {
const results = await users.insertOne(user)
return results.ops[0]
} catch (error) {
throw error
}
}
const getUsers = async (users) => {
try {
const results = await users.find().toArray()
return results
} catch (error) {
throw error
}
}
const findUserById = async (users, id) => {
try {
if (!ObjectID.isValid(id)) throw 'Invalid MongoDB ID.'
const results = await users.findOne(ObjectID(id))
return results
} catch (error) {
throw error
}
}
// Export garbage as methods on the User object
module.exports = { createUser, getUsers, findUserById }