Return 404 in MongoDB block - node.js

I use follow codes to insert something into mongodb, and if it is successfully insertted, I should get string with information success
if (email) {
MongoClient.connect(dbUrl, { useNewUrlParser: true }, function(err, db) {
if (err) throw err;
const dbo = db.db("email");
const dbObj = {email: email};
dbo.collection("email").insertOne(dbObj, function(err, res) {
if (err) throw err;
ctx.body = "success";
db.close();
});
});
} else {
ctx.body = "email is missing";
}
And now the document can be inserted into mongodb, but the get 404 Not Found, any ideas?

Related

TypeError: login.findOne(...).toArray is not a function

I have this function, whcih bascially gets the usernmae and password of the users input from the front-end form, and then checks it in mongodb:
app.post('/login', (req, res, next) => {
var username = req.body.username;
var password = req.body.password;
//connecting to the mongo client
client.connect().then (() => {
//defining database name and collection
const database = client.db("myFirstDatabase");
const login = database.collection("login");
//connecting to the mongo client
MongoClient.connect(uri, function(err, db) {
if (err) throw err;
//finding all documents inside array
login.findOne({"username": username}).toArray(function(err, result) {
if (err) throw err;
result.forEach(results =>
bcrypt.compare(password, results.password, function(err, result) {
if (result === true) {
req.session.loggedin = true
next()
} else {
res.redirect('/login')
}
})
);
db.close();
});
});
})
})
however, it is giving me this error:
TypeError: login.findOne(...).toArray is not a function
i've never encountered this error before. how do i fix this?
Try this way
login.findOne({"username": username}, function(err,user)
{ console.log(user); });

Mongodb find not printing json data

In the code I am trying to find all documents with code UE19CS204.But in the console.log
a big message is printed not the JSON data.The findOne() is working but not find().
I don’t know what change to do to find all documents with code UE19CS204.
var MongoClient = require(‘mongodb’).MongoClient;
var url = “mongodb://localhost:27017/”;
MongoClient.connect(url, { useUnifiedTopology: true } ,function(err, db) {
if (err) throw err;
var dbo = db.db(“pes”);
dbo.collection(“course”).find({“code”:“UE19CS204”}, function(err, result) {
if (err) throw err;
console.log(result);
});
dbo.collection(“course”).findOne({code:“UE19CS204”}, function(err, result) {
if (err) throw err;
console.log(result);
db.close();
});
});
The method find() creates a cursor for a query that can be used to iterate over results from MongoDB, see here.
Use toArray(), you can finde the documentation here.
dbo.collection(“course”).find({“code”:“UE19CS204”}).toArray(function(err, docs) {
if (err) {
throw err;
}
console.log(docs);
})
Full example:
const MongoClient = require('mongodb').MongoClient;
// Connection URL
const url = 'mongodb://localhost:27017';
// Database Name
const dbName = 'pes';
// Collection Name
const collectionName = 'course';
// Filter
const filter = { 'code': 'UE19CS204' }
// Use connect method to connect to the server
MongoClient.connect(url, { useUnifiedTopology: true }, function(err, client) {
if (err) {
throw err;
}
client.db(dbName).collection(collectionName).find(filter).toArray(function(err, docs) {
if (err) {
throw err;
}
console.log(docs);
})
client.close();
});

Error-handling in asynch functions

I want to throw an error into the console if the following function doesn't work for any reason. It's getting some data from a website, writing them into a mongoDB.
If for example the insert into mongoDB or the scraping fails I want to get an error message in the console. I have no idea how to archive proper error-handling with nodejs (0 clue about promises and stuff).
artikel.getData(async () => { for (let i = 0; i < arrayOfArticles.length; i++){
await scrape(i).then((price) => {
console.log('Data ' + arrayOfArticles[i] + ': ' + received);
//Connect to DB
MongoClient.connect(url, {useNewUrlParser: true}, function(err, db) {
if (err) throw err;
let dbo = db.db("testDB");
let insertPart = {
name: arrayOfArticles[i],
site: dealer,
price: price
};
dbo.collection("testcollection").insertOne(insertPart, function(err, res) {
if (err) throw err;
console.log(divide);
console.log("Document inserted");
console.log(divide);
db.close();
});
});
});
}
});
You should not write DB connection code inside the loop or inside API. It should be in some config file.
You don't need to write .then with await, use try-catch for error handling.
artikel.getData(() => {
MongoClient.connect(url, {
useNewUrlParser: true
}, async function (err, db) {
for (let i = 0; i < arrayOfArticles.length; i++) {
try {
const price = await scrape(i);
//Connect to DB
if (err) throw err;
let dbo = db.db("testDB");
let insertPart = {
name: arrayOfArticles[i],
site: dealer,
price: price
};
dbo.collection("testcollection").insertOne(insertPart, function (err, res) {
if (err) {
console.log(err);
throw err
};
console.log(divide);
console.log("Document inserted");
console.log(divide);
});
} catch (error) {
console.log(error);
}
}
db.close();
});
});

Mongodb.connect does not execute callback function

Im trying to connect to my Mongodb and insert some documents if they are not already in the db. It works fine with the first inserts but in the function existInDatabase it sometimes does not execute the callback function.
var MongoClient = require('mongodb').MongoClient;
var mongoData = require('./mongoData');
var exports = module.exports = {};
var dbName = 'checklist';
MongoClient.connect(mongoData.ConString, {
useNewUrlParser: true
}, function(err, db) {
if (err) throw err;
for (var key in mongoData.Customers) {
if (!existsInDatabase(mongoData.Customers[key], 'Customers')) {
db.db(dbName).collection('Customers').insertOne(mongoData.Customers[key], function(err, res) {
if (err) throw err;
console.log('1 document inserted');
db.close();
});
}
}
for (var key in mongoData.Categorys) {
if (!existsInDatabase(mongoData.Customers[key], 'Customers')) {
db.db(dbName).collection('Categorys').insertOne(mongoData.Categorys[key], function(err, res) {
if (err) throw err;
console.log('1 document inserted');
db.close();
});
}
}
});
function existsInDatabase(obj, collection) {
var result = false;
MongoClient.connect(mongoData.ConString, {
useNewUrlParser: true
}, function(err, db) {
db.db(dbName).collection(collection).find({}).forEach(function(doc) {
if (doc.id == obj.id) {
result = true;
}
}, function(err) {
console.log(err);
});
});
return result;
}
I have made a few changes to your code. It seems you are new to async programming, spend some time to understand the flow. Feel free for any further query. Here is your code.
// Welcome to aync programming
// Here no one waits for the slow processes
var MongoClient = require('mongodb').MongoClient;
var mongoData = require('./mongoData');
var exports = module.exports = {};
var dbName = 'checklist';
// Make the connection for once only
MongoClient.connect(mongoData.ConString, { useNewUrlParser: true },
function(err, db) {
if (err) throw err;
var myDB = db.db(dbName); // create DB for once
for (var key in mongoData.Customers) {
//make call to the function and wait for the response
existsInDatabase(mongoData.Customers[key], 'Customers', function(err, result) {
//once the response came excute the next step
if (result) {
myDB.collection('Customers').insertOne(mongoData.Customers[key], function(err, res) {
if (err) throw err;
console.log('1 document inserted');
});
}
});
}
for (var key in mongoData.Categorys) {
//make call to the function and wait for the response
existsInDatabase(mongoData.Customers[key], 'Customers', function(err, result) {
//once the response came excute the next step
if (result) {
myDB.collection('Categorys').insertOne(mongoData.Categorys[key], function(err, res) {
if (err) throw err;
console.log('1 document inserted');
});
}
});
}
// Both the for loop will work randomly without any order
function existsInDatabase(obj, collection, cb) {
var result = false;
myDB.collection(collection).findOne({ id: obj.id }, function(err, result)
{
if (err) {
//this cb will work only when db operation is complited
cb(err);
} else if (result) {
cb(null, true);
} else {
cb(null, false);
}
});
}
});
This code may result in some error. Feel free to ask more questions over it
db.db(dbName).collection(collection).find({}) returns a cursor per the docs. You are missing .toArray():
db.db(dbName).collection(collection).find({}).toArray()...

Finish execution if first query returns a value Node.js Express.js mongoDB

Before starting, please mind that i have been searching this over 2+ hours, the answer will be simple i know but i couldnt get it to work . i am new to express node mongodb,
MongoClient.connect(url, function(err, db) {
if (err) {
res.status(err.status); // or use err.statusCode instead
res.send(err.message);
}
var usernameGiven = req.body.usernameGiven;
//Select the database
var dbo = db.db("notifellow");
//run the query
var query = { username: usernameGiven , friends: []};
dbo.collection("users").findOne({ username: usernameGiven}, function(err, result) {
if (err){
res.status(err.status); // or use err.statusCode instead
res.send(err.message);
console.log("Query Error Occured!");
}
else {
if (result) {
//Send the response
res.send("EXISTS");
//I WOULD LIKE TO EXIT IF THIS LINE EXECUTES
}
}
});
dbo.collection("users").insertOne(query, function(err, result) {
if (err){
res.status(err.status); // or use err.statusCode instead
res.send(err.message);
console.log("Query Error Occured!");
}
else {
if (result) {
//Send the response
res.send("CREATED 201");
} else {
res.send("Failed to insert");
}
}
});
db.close();
});
my goal is to check if an user doesnt exists with given username, i would like to insert that to the DB.
i would like to exit if my query finds an match and arrange such that insertOne wont execute. please enlighten me!!
Once you are not using the async/await syntax you will have to nest the calls to MongoDB, so they execute in series. You can also use a module like async to achieve this.
MongoClient.connect(url, function(err, db) {
if (err) {
res.status(err.status); // or use err.statusCode instead
res.send(err.message);
}
var usernameGiven = req.body.usernameGiven;
//Select the database
var dbo = db.db("notifellow");
//run the query
var query = { username: usernameGiven , friends: []};
dbo.collection("users").findOne({ username: usernameGiven}, function(err, result) {
if (err){
res.status(err.status); // or use err.statusCode instead
db.close();
console.log("Query Error Occured!");
return res.send(err.message);
}
if (result) {
db.close();
return res.send("EXISTS");
}
dbo.collection("users").insertOne(query, function(err, result) {
if (err){
res.status(err.status); // or use err.statusCode instead
db.close();
console.log("Query Error Occured!");
return res.send(err.message);
}
db.close();
if (result) {
return res.send("CREATED 201");
}
res.send("Failed to insert");
});
});
});
Try this
dbo.collection("users").findOne({ username: usernameGiven}, function(err, result) {
if (err){
//put the error logic
}
else {
if (result) {
//Send the response
return result;
}
else{
// if above if block fails it means that user does not exist
//put the insert logic
}
});

Resources