Trying to get message history from a db collection( mongodb) - node.js

I'm back with my chat system with history, using mongodb, I can't have let's say about the last 20 messages from the db colection, I'm quite sure it is about some filtering to add into the find() routine, but I don't know where and how to do that here is my piece of code :
MongoClient.connect('mongodb://127.0.0.1:27017/gt-chat', function(err, db) {
if(err) throw err;
var collection = db.collection('gt-chat');
console.log("******************************Printing docs from Cursor Each")
collection.find().each(function(err, doc) {
console.log(doc);
if(doc != null) {
console.log("Doc from Each ");
console.dir(doc);
}
});
});
this code is showing :
{ _id: 5488473660eda4ac251d6688,
message: 'The quick brown fox jumps over the lazy dog' }
and I don't need the _id value, I only want the last 20 messages as result.
Hoping to be clear enough,
Thanks in advance for your help on this ! :)

You could try this:
MongoClient.connect('mongodb://127.0.0.1:27017/gt-chat', function(err, db) {
if(err) throw err;
var collection = db.collection('gt-chat');
console.log("******************************Printing docs from Cursor Each")
collection.find({}, {_id: 0}).sort({$natural: 1}).limit(20).each(function(err, doc) {
console.log(doc);
if(doc != null) {
console.log("Doc from Each ");
console.dir(doc);
}
});
});
EDIT
To write to browser, use the response object as follows
require('http').createServer(function(req, res) {
MongoClient.connect('mongodb://127.0.0.1:27017/gt-chat', function(err, db) {
if(err) throw err;
var collection = db.collection('gt-chat');
console.log("******************************Printing docs from Cursor Each")
collection.find({}, {_id: 0}).sort({$natural: 1}).limit(20).each(function(err, doc) {
console.log(doc);
if(doc) {
res.writeHead(200, {"Content-Type": "text/plain"});
res.write(JSON.stringify(doc) + "\n");
}
else {
res.end();
}
});
});
}).listen(port, host);

Related

How to compare input and Document in mongoDB

When I Register [ input Email / password to DB ] success. Then, I want to login. If input[email/pass] == document in collection >> go to next page, else console.log['wrong email/pass']
I try to wirte IF/else code but I don't know check condition.
This code is Register form
app.post('/register',function(req,res){
MongoClient.connect(url, function(err, db) {
if (err) throw err;
let dbo = db.db("project");
let myobj = { Email: req.body.email, Password: req.body.psw } ;
dbo.collection("Register").insertOne(myobj, function(err, res) {
if (err) throw err;
console.log(" document inserted");
db.close();
});
});
});
This code is Login form
app.post('/index',function(req,res){
MongoClient.connect(url, function(err, db) {
if (err) throw err;
let dbo = db.db("project");
let cursor = dbo.collection('Register').find();
cursor.each(function(err,doc) {
if (doc == req.body.email && req.body.psw){
console.log("goto next page");
}
else{
console.log('wrong');
}
});
db.close();
});
});
Correct input and wrong input Output is = Wrong
Pls insert loop check all of array pls.
app.post('/index',function(req,res){
MongoClient.connect(url, function(err, db) {
if (err) throw err;
var dbo = db.db("project");
dbo.collection("Register").findOne({}, function(err, result) {
if (result.Email == req.body.email && result.Password == req.body.psw) {
console.log("OK");
}
else{
console.log(result.Email && result.Password);
}
db.close();
});
});
});
You have to compare individual values, like so:
if (doc.Email == req.body.email && doc.Password == req.body.psw){
console.log("goto next page");
}
Firstly you should check for valid request body and the you should do a fineone query instead of running a for-loop and checking. see the corrected one below :
app.post("/index", function(req, res) {
let {
email,
psw
} = req.body;
if (email && psw) {
console.log("wrong credentials");
return;
} else {
MongoClient.connect(url, function(err, db) {
if (err) throw err;
let dbo = db.db("project");
let data = dbo.collection("Register").findOne({
Email: email,
Password: psw
});
if (data) {
console.log("goto next page");
} else {
console.log("wrong");
}
db.close();
});
}
});
I'm late to the party but I just found a solution to a similar problem and wanted to share.
If you have input values in javascript and want to use them in a mongodb query you need to make them in to strings.
Assuming user._id is a value coming from a javascript function call.
This will work:
{ userId: { $eq: ${user._id} } } ✅
This won't work:
{ userId: { $eq: user._id } } ❌

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
}
});

How to find a record and insert the same record in Mongoose?

Here I want to get a record and I need to insert the same record with slight modification. But I can't see the data in my new record which I found in my get record. Here is what I tried, can anyone help me? I think the problem is with this line var institution = new Institution(data);:
Institution.find({_id:i._id}).exec(function (err, result) {
if(result)
transferData(result);
}
});
});
}
function transferData(data){
var institution = new Institution(data);
institution.name = 'xxxx';
institution.save(function (err, data) {
if (err) {
return res.status(400).send({ message: errorHandler.getErrorMessage(err) });
} else {
console.log('Data Inserted Successfully');
}
});
}
find() returns an array of docs that match the criteria in the callback hence the line
var institution = new Institution(data);
will not work as it's expecting a Document not an array.
You could use findById() method as:
Institution.findById(i._id).exec(function (err, result) {
if (result) transferData(result);
});
function transferData(data) {
var institution = new Institution(data);
institution.name = 'xxxx';
institution.save(function (err, data) {
if (err) {
return res.status(400).send({ message: errorHandler.getErrorMessage(err) });
} else {
console.log('Data Inserted Successfully');
}
});
}
A much better approach would involve the findByIdAndUpdate() method:
Institution.findByIdAndUpdate(i._id, {name: 'xxxx'}, {upsert: true}, function (err, data) {
if (err) {
return res.status(400).send({ message: errorHandler.getErrorMessage(err) });
} else {
console.log('Data Inserted Successfully');
}
);

for loop giving an error while inserting document to collection

In node.js I am writing query to insert document to collection, but that query inserting only one document. Below the js code is,
app.js
router.post('/creatList', function(req,res){
console.log(req.body.email);
var emails = req.body.email;
if(req.body.wData.wishListType == 'Shared'){
var findUsers = function(db, callback) {
var cursor;
cursor = db.collection('users').find({email: { $in: emails }})
cursor.toArray(function(err, docs){
if(err){
callback(new Error("Some problem"));
} else {
callback(null,docs);
}
});
};
MongoClient.connect(config.database, function(err, db) {
assert.equal(null, err);
findUsers(db, function(err,docs) {
db.close();
console.log(docs);
var inserts_processing = 0;
for(var key in docs){
console.log(key);
var ids = docs[key]._id;
inserts_processing++;
console.log(ids);
var insertDocument = function(db, callback) {
db.collection('notifications').insertOne({
"userId" : ids,
},function(err, result) {
inserts_processing--;
assert.equal(err, null);
console.log("Inserted a document into the notifications collection.");
if(inserts_processing == 0){
db.close();
callback();
}
});
};
MongoClient.connect(config.database, function(err, db) {
assert.equal(null, err);
insertDocument(db, function() {
db.close();
});
});
}
});
});
} else {
console.log("other");
}
});
In the above code console.log contains two ids 570dec75cf30bf4c09679deb
56fe44836ce2226431f5388f but actually it inserting only last one.
According to your updated code I will try the following
router.post('/creatList', function(req,res){
console.log(req.body.email);
var emails = req.body.email;
if(req.body.wData.wishListType == 'Shared'){
// Open one connection to find users and insert documents
MongoClient.connect(config.database, function(err, db) {
assert.equal(null, err);
if(!err){
findUsers(db, function(err,docs) {
if(!err){
insertDocs(db, docs, function(){
db.close(); // Close connection
console.log("All documents have been inserted");
res.status(200).send("All is OK");
});
}
});
});
}
} else
console.log("other");
});
function insertDocs(db, docs, callback){
var inserts_processing = 0; // Will contain the number of inserts pending operation
for(var key in docs){
var ids = docs[key]._id;
inserts_processing++; // Before writing data, add one to processing inserts
db.collection('notifications').insertOne({
"userId" : ids,
}, function(err, result) {
inserts_processing--; // One insert have been finished, so remove one
assert.equal(err, null);
console.log("Document inserted into the notifications collection.");
// If all inserts have been finished, call back the function
if(inserts_processing == 0)
callback();
});
}
}
function findUsers(db, callback) {
var cursor;
cursor = db.collection('users').find({email: { $in: emails }})
cursor.toArray(function(err, docs){
if(err)
callback(new Error("Some problem"));
else
callback(null,docs);
});
};

Nodejs controller not working properly

router.get('/roomlist', function(req, res) {
var db = req.db;
var collection = db.get('roomlist');
collection.find(function(e,docs){
res.render('roomlist', {
"roomlist" : docs
});
});
});
The above controller is used to get list of rooms under a table "ROOMLIST". I need to get the details. I need to display all the roomname in the table ROOMLIST.
You should use find method of mongodb to get the documents from a collection. And then use cursor to iterate through the documents.
var getRoomlist = function(db, callback) {
var cursor =db.collection('roomlist').find( );
cursor.each(function(err, doc) {
assert.equal(err, null);
if (doc != null) {
return callback(false, doc);
} else {
return callback(true, null);
}
});
};
Then you can use your route /roomlist, to call the function getRoomlist when it gets hit and render the doc.
router.get('/roomlist', function(req, res){
programLogic(function(err, doc){
if(err){
console.log(err);
}
return res.send(doc);
});
});
If you still don't get it, just clone this and run through it
var programLogic = function (cb){
MongoClient.connect(url, function(err, db) {
assert.equal(null, err);
getRoomlist(db, function(err, doc) {
if(err){
console.log(err);
}
return cb(false, doc);
});
});
}// programLogic ends
var getRoomlist = function(db, callback) {
var cursor =db.collection('roomlist').find( );
cursor.each(function(err, doc) {
assert.equal(err, null);
if (doc != null) {
return callback(false, doc);
} else {
return callback(true, null);
}
});
};
router.get('/roomlist', function(req, res){
programLogic(function(err, doc){
if(err){
console.log(err);
}
return res.send(doc);
});
});
Which engine do you use for views rendering? Based on error message, property "roomname" has been interpreted as a partial, and cannot be found in views directory.

Resources