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();
});
Related
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?
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();
});
});
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()...
db.getCollection('Leave').find({},{_id:0 ,
Can_It_Be_carry_forwarded:1})
this is working perfectly in the MongoDb Client CMD But not in the Below Code
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/Chatbot_Project";
MongoClient.connect(url, function(err, db) {
if (err) throw err;
var dbo = db.db("Chatbot_Project");
dbo.collection('Leave').find({}, {Can_It_Be_carry_forwarded:1}).toArray(function(err, result) {
if (err)
throw err;
console.log(result);
db.close();
})
});
Your problem is the find method, you are missing the projection field.
If you want to retrive only the Can_It_Be_carry_forwarded field you need the following: {projection:{Can_It_Be_carry_forwarded:1, _id: 0}} as the second argument.
Solution from a similar question: https://stackoverflow.com/a/48294672/4120554
Documentation: http://mongodb.github.io/node-mongodb-native/3.0/api/Collection.html#find
Try this:
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/Chatbot_Project";
MongoClient.connect(url, function(err, db) {
if (err) throw err;
var dbo = db.db("Chatbot_Project");
dbo.collection('Leave').find({},{projection:{_id: 0, Can_It_Be_carry_forwarded:1}}).toArray(function(err, result) {
if (err)
throw err;
console.log(result);
db.close();
})
});
I have an issue with the asynchrous programming model in Node.js.
I know this has been asked before, but so far I haven't found anything that I can use to solve my issue.
How do I force console.log from running before dbQueryName has been invoked and username has gotten its value from it?
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/";
function dbQueryName() {
MongoClient.connect(url, function(err, db) {
if (err) throw err;
var dbo = db.db("mydb");
dbo.collection("users").findOne({}, function(err, result) {
if (err) throw err;
return result.name
db.close();
});
});
}
var username = dbQueryName();
// Wait until dbQueryName() has been invoked and username has gotten its value before running this
console.log(username);
I have managed to get it working using a callback parameter in the function, but is there a way to do this with less code and indentation?
function dbQueryName(callback) {
MongoClient.connect(url, function(err, db) {
if (err) throw err;
var dbo = db.db("mydb");
dbo.collection("users").findOne({}, function(err, result) {
if (err) throw err;
callback(result.name)
db.close();
});
});
}
dbQuery(function(result){
var username = result
console.log(username);
});
Yes if you are not passing a callback to MongoClient.connect or collection.findOne, it returns a promise.
But you need to add another function to use async await
init()
async function dbQueryName() {
const db = await MongoClient.connect(url);
const dbo = db.db("mydb");
const user = await dbo.collection("users").findOne({})
return user.name
}
async function init() {
try {
const name = await dbQueryName()
} catch (error) {
console.log(error);
}
}