Show Error if Duplicate found in ensureIndex MongoDB Node - javascript

I have successfully stopped duplicate entries in MongoDB Database, But my issue is whenever a duplicate entry called, it was not returning any error and just stopping the node server
How to throw any custom error like res.send('duplicate entry')..
i am using forever start server.js for non stop server.
Here below the code for my issue..
router.route('/new_order')
.post(function(req, res, next){
var order_no = req.body.order_no;
var origin_port = req.body.origin_port;
var destination_port = req.body.destination_port;
var expected_date = req.body.expected_date;
var status = 0;
var item = {
order_no: order_no,
origin_port: origin_port,
destination_port: destination_port,
expected_date: expected_date,
status: status
};
var url = 'mongodb://localhost:27017/transport_main';
mongo.connect(url, function(err, db){
assert.equal(null, err);
db.collection('orders').ensureIndex( { order_no: 1 }, {unique:true}, function(err){
db.collection('orders').insertOne(item, function(err, result){
assert.equal(null, err);
console.log('New Order Insterted');
db.close();
res.send('true');
});
});
});
});
Thanks in advance

Add the following:
db.collection('orders').ensureIndex( { order_no: 1 }, {unique:true}, function(err){
if(err) return res.send("You are already registered");...

Solved This issue
11000 is the Duplicate error code which calls while trying to insert. Not while ensureIndex.
ensureIndex was just checking the index created or not, if not it will re-create for us.
important : remove "assert.equal(null, err)" while attempting to insert.
mongo.connect(url, function(err, db){
assert.equal(null, err);
db.collection('orders').ensureIndex( { order_no: 1 }, {unique:true}, function(err, result){
db.collection('orders').insertOne(item, function(err, result){
console.log(err);
if (err) {
if (err.code == 11000) {
res.end('Duplicate Entry Found');
}
}
console.log('New Order Insterted');
db.close();
res.send('true');
});
});
});

Related

Undefined result in MongoDB and Node js

I want to get my collection data, my collection is named students and is part of my pool database.
The connection to the mongoDB works, however console.log(result.lastname) returns undefined.
Here is my server.js file
var mongo = require('mongodb');
var assert = require('assert');
const url = 'mongodb://localhost:27017/';
mongo.connect(url, function (err, db) {
if(err) {
console.log("Connection failed");
}
console.log("Connection successfull");
var dbo = db.db("pool");
dbo.collection("students").find({}, function(err, result) {
if (err) throw err;
console.log(result.lastname);
db.close();
});
});
And the content in my students collection that I see using db.students.find(); directly in console
{ "_id" : ObjectId("5eb1570f2c0167c90cc127fd"), "id" : 0, "lastname" : "Sam", "firstname" : "Sung", "email" : "sc#mail.com", "phone" : 613295990, "validated" : "Validated", "admin" : true }
According to this link:
https://docs.mongodb.com/manual/reference/method/db.collection.find/
.find() returns a list and not just one entry. Meaning even though your collection has one entry, it will be received as a list with just one entry.
You have to iterate.
So, try this:
var mongo = require('mongodb');
var assert = require('assert');
const url = 'mongodb://localhost:27017/';
mongo.connect(url, function (err, db) {
if(err) {
console.log("Connection failed");
}
console.log("Connection successfull");
var dbo = db.db("pool");
dbo.collection("students").find({}, function(err, result).toArray(function(err, result) {
if (err) throw err;
console.log(result.lastname);
db.close();
});
});
Another helpful link : https://www.w3schools.com/nodejs/nodejs_mongodb_find.asp
I think it is returning an array, can you try:
result[0].lastname

MongoDB is connecting but does not update

I have not used MongoDB with NodeJS for a while so I am a bit rusty. I have written the code below and it is connecting properly but for some reason, the values are not updating. Can someone tell me what is wrong with my code?
MongoClient.connect(url, function(err, db) {
console.log("Connected successfully to Mongodb: Log Request (token and sender)");
var query = {sender:senderThatAsked};
db.collection("requestFrom").updateOne(
query,
{$set:{date: new Date(Date.now()).toISOString()}},
{$setOnInsert: {
token:tokenUsed,
date: new Date(Date.now()).toISOString(),
count: 0,
sender:senderThatAsked }},
{upsert: true}, function(err,res){
if (err) throw err;
console.log('The request has been logged! Now Finding...');
db.close();
});
});
Thanks in advance.
MongoClient.connect(url, function(err, db) {
console.log("Connected successfully to Mongodb: Log Request (token and sender)");
var query = {sender:senderThatAsked};
db.collection("requestFrom").updateOne(
query,
{
$set:{date: new Date(Date.now()).toISOString()},
$setOnInsert: {
token:tokenUsed,
count: 0,
sender:senderThatAsked
}
},
{upsert: true}, function(err,res){
if (err) throw err;
console.log('The request has been logged! Now Finding...');
db.close();
});
});
put $set and $setOnInsert in one object please

MongoDB get data to display in HTML

I'm trying to display mongodb data in my html page. I've already managed to insert data in db but for some reason my "get" function does not work.
I'm using node.js with express framework and Angular for front-end and routing.
This is my "get" function to retreive data from MongoDB:
var mongo = require('mongodb');
var assert = require('assert');
var url = 'mongodb://localhost:27017/loodgieters';
router.get('/get-data', function(req, res, next) {
var resultArray = [];
mongo.connect(url, function(err, db){
assert.equal(null, err);
var cursor = db.collection('user-data').find();
cursor.forEach(function(doc, err){
assert.equal(null, err);
resultArray.push(doc);
}, function(){
db.close();
res.render('index', {items: resultArray});
});
});
});
And my "post" which works
router.post('/insert', function(req, res, next) {
var item = {
name: req.body.name,
adress: req.body.adress,
postal: req.body.postal,
city: req.body.city,
email: req.body.email,
phone: req.body.phone,
quotation: req.body.quotation,
message: req.body.message
};
mongo.connect(url, function(err, db) {
assert.equal(null, err);
db.collection('user-data').insertOne(item, function(err, result){
assert.equal(null, err);
console.log('Item inserted');
db.close();
});
});
res.redirect('/contact');
});
i am not sure if this is the correct way to open and close mongo connection each time you are trying to query .
if you want to go for another approach then use mongoose
and follow something like this
https://pastebin.com/g7aatzzj
I think that you have a mistake in your .find().forEach function callbacks. The error handling seems to be in the endCallback not the iteratorCallback.
According to the official doc, the correct way should be :
var mongo = require('mongodb');
var assert = require('assert');
var url = 'mongodb://localhost:27017/loodgieters';
router.get('/get-data', function(req, res, next) {
var resultArray = [];
mongo.connect(url, function(err, db){
assert.equal(null, err);
var cursor = db.collection('user-data').find({});
cursor.forEach(function(doc){
assert.notEqual(null, doc);
resultArray.push(doc);
}, function(err, doc){
assert.equal(null, err);
db.close();
res.render('index', {items: resultArray});
});
});
});
This can also be found in their unit tests
var cursor = collection.find({})
.map(function(x) { return {a:1}; })
.batchSize(5)
.limit(10);
cursor.forEach(function(doc) {
test.equal(1, doc.a);
}, function(err, doc) {
test.equal(null, err);
db.close();
test.done();
});
I think that you must have a error that is not passed to the first callback and not handled in the second one. So you do not see the error.
Try to insert an empty object to the find() function as following:
var cursor = db.collection('user-data').find({});
I have just run your code and modified it a bit for my purposes.
Please find the following snippet
//Instantiate MongoClient
var mongo = require('mongodb').MongoClient;
//Assert library (Perhaps overkill if you are writing production-level code)
var assert = require('assert');
//Express engine
var express = require('express');
//URL for my mongo instance
//Connecting to the blog database
var url = 'mongodb://localhost:27017/blog';
//Instantiate express
var router = express();
//Get operation
router.get('/get', function(req, res, next) {
var resultArray = [];
mongo.connect(url, function(err, db){
assert.equal(null, err);
var cursor = db.collection('posts').find();
cursor.forEach(function(doc, err){
assert.equal(null, err);
resultArray.push(doc);
}, function(){
db.close();
//I have no index file to render, so I print the result to console
//Also send back the JSON string bare through the channel
console.log(resultArray);
res.send(resultArray);
});
});
});
//Start listeninig
//Hardcoded port 1000
var server = router.listen(1000, function() {
var host = server.address().address;
var port = server.address().port;
console.log("Content Provider Service listening at http://%s:%s", host, port);
});
Therefore to get this working for you:
Change the url to 'mongodb://localhost:27017/loodgieters';
Change router to '/get-data'
I hope this helps!
Also consider using splitting the implementation of the get operation to another module to help for the Separation of Responsibilities to make your code more robust.

MongoDB output to browser

Hello I'm learning mongoDB and trying to print out my database query results to the browser.
I have a program working where it writes the output JSON to the console using console.log()
Is there a way to use res.send() (using express) or response.write() and response.send() to simply output the raw JSON data that the database query gets?
In other words, How can I make my database invokatation return a string?
// Use connect method to connect to the server
var invokeDatabase = function() {
MongoClient.connect(url, function(err, db) {
assert.equal(null, err);
console.log("Connected successfully to database server");
findDocuments(db, function() {
findDocumentsFiltered(db, function() {
db.close();
});
});
});
};
//routes
app.get('/', function(req, res) {
console.log("Someone connected.")
res.send("accessing database... " + invokeDatabase())
//res.send('Welcome G')
})
This example may help you to understand
// Use connect method to connect to the server
var invokeDatabase = function(callback) {
MongoClient.connect(url, function(err, db) {
//assert.equal(null, err);
if(err) {
console.log("Unable to connect database");
callback(err, null);
return;
}
console.log("Connected successfully to database server");
findDocuments(db, function() {
findDocumentsFiltered(db, function(err, data) {
callback(err, data);
db.close();
});
});
});
};
//Added for demo. Here users is collection
var findDocumentsFiltered = function(db, callback) {
db.collection('users').find({}).toArray(function(err, userList) {
callback(err, userList);
});
};
//routes
app.get('/', function(req, res) {
console.log("Someone connected.")
invokeDatabase(function(err, data) {
if(err)
res.status(500).json({error: err});
else
res.json(data);
}))
//res.send('Welcome G')
})

How to delete document by _id using MongoDB and Jade (Express.js)?

I have successfully set up a database using mongodb, and I have managed to add new entries to my collection. However, when I use a similar method to delete, nothing happens.
Express.js code
router.post('/deleteproject', function(req, res) {
var MongoClient = mongodb.MongoClient;
var url = 'mongodb://localhost:27017/plugd';
MongoClient.connect(url, function(err, db) {
if (err) {
console.log("Unable to connect to server", err);
} else {
console.log('Connected to server');
var collection = db.collection('projects');
collection.remove(
{_id: new mongodb.ObjectID(req.body)}, function(err, result) {
if (err) {
console.log(err);
} else {
res.redirect("thelist");
}
db.close();
});
}
});
});
Jade code
h2.
ul
Projects
each project, i in projectlist
#project_list_item
a(href='#') #{project.owner} - #{project.project}
p #{project.ref1}
p #{project.ref2}
p #{project.ref3}
form#form_delete_project(name="deleteproject", method="post", action="/deleteproject")
input#input_name(type="hidden", placeholder="", name="_id", value="#{project._id}")
button#submit_project(type="submit") delete
I figured it out. Here is my fix for deleting data from a mongodb collection using a router in express.js.
Express.js
router.post('/deleteproject', function(req, res) {
var MongoClient = mongodb.MongoClient;
var ObjectId = require('mongodb').ObjectId;
var url = 'mongodb://localhost:27017/app';
MongoClient.connect(url, function(err, db) {
if (err){
console.log('Unable to connect to server', err);
} else {
console.log("Connection Established");
var collection = db.collection('projects');
collection.remove({_id: new ObjectId(req.body._id)}, function(err, result) {
if (err) {
console.log(err);
} else {
res.redirect("thelist");
}
db.close();
});
}
});
});
Jade code
extends layout
block content
h2.
Projects
ul
each project, i in projectlist
#project_list_item
a(href='#') #{project.owner} - #{project.project}
p #{project.ref1}
p #{project.ref2}
p #{project.ref3}
form#form_delete_project(name="deleteproject", method="post", action="/deleteproject")
input#input_name(type="hidden", placeholder="", name="_id", value="#{project._id}")
button#submit_project(type="submit") delete
The jade file is rendering to a page called 'thelist' that lists each item in the collection.
The form section handles the delete function for each item in the list.
This works for me as long as I keep Jade's indents happy :)
Try this and see if it works :
router.post('/deleteproject', function(req, res) {
var MongoClient = mongodb.MongoClient;
var url = 'mongodb://localhost:27017/plugd';
MongoClient.connect(url, function(err, db) {
if (err) {
console.log("Unable to connect to server", err);
} else {
console.log('Connected to server');
var collection = db.collection('projects');
collection.remove(
{_id: req.body}, function(err, result) {
if (err) {
console.log(err);
} else {
res.redirect("thelist");
}
db.close();
});
}
});
});
Since you're on MongoDB's Node.js Native Driver, you don't need to marshall _id inside ObjectId. You can directly specify the _id as string

Categories

Resources