index a mongo db with javascript - javascript

I have working script which stores the html forms i have created in mongoDB. It works awesome. However, i can't search any of the data i place in mongo, because i don't have an index.
I realize I could create the index from the console, but for my system to work the way we need, I really need the index to be created when the data is stored. So, i need to place code in the javascript that actually creates the code 9using node.js or directly).
I tried the following javascript (with node.js), but it does not appear to work.
app.post('/:db/:collection/formSubmit', function(req, res) {
var json = form2json.transform(req.rawBody);
var db = new mongo.Db(req.params.db, new mongo.Server(config.db.host, config.db.port,mongoOptions ));
db.open(function(err, db) {
db.authenticate(config.db.username, config.db.password, function () {
db.collection(req.params.collection, function(err, collection) {
collection.insert(Array.isArray(json) ? json[0] : json, function(err, docs) {
res.header('Content-Type', 'application/json');
if(req.is('application/xml')) {
res.send('<ok>1<ok>')
} else {
es.send(json, 201);
}
// my attempt to create an index while posting a form follows
db.core.ensureIndex( { "document": 1 } )
db.close();
});
});
});
});
});

You need to call ensureIndex on the collection:
collection.ensureIndex({ "document": 1 }, function (err, indexName) {
db.close();
});

Related

NodeJs Perform Operation on Each returned MySql Result Object

Im using NodeJs to fetch data from mysql database, from the result object/array i want to perform specific action (call web service) with data returned from mysql. unfortunately whenever i iterate through mysql result and call web service only one object from the mysql resultset is called against web service. Here are my codes.
app.get('/blt', function(req, res){
var sql = "SELECT dest, amt FROM dit WHERE dest != 'DEST' && amt != 'AMT'";
pool.getConnection(function(err, conn){
if(err){
console.log("MYSQL Connection Error: "+err);
}
else{
conn.query(sql, function(err2, result){
if(err2){
console.log("Some error: "+err2);
}
else{
//console.log(JSON.stringify(result));
Object.keys(result).forEach(function(key) {
let result_ = result[key];
let sn = Math.floor((Math.random() * 900000000) + 100000000);
let dacc_ = result_.dest;
console.log(dacc_);
let blDetail = {
"BalDto": {
"Src": "XXXXXX",
"Code": 1,
"Amt": 10,
"Dac": dacc_, //Variable from mysql resultset
"Cmt": "Ok",
"SN": sn
}
};
soap.createClient(url, function(err, client) {
client.addSoapHeader(AuthHeader);
client.BalTransfer(blDetail, function(err, result) {
if (err) {
console.log(err.body);
} else {
console.log("done");
}
});
});
}
);
}
conn.release(function(errs){
if(errs){
console.log(errs)
}
});
});
}
});
});
I tried to use async but still i got the same results, only one of the returned mysql result set is sent to web service.
I want all the result set to be sent to webservice one by one, Kindly Help
You're literally iterating through your response from MySQL, which is a list of something, then you're making the soap call on every single one of them.
What you need to do is this:
Check the soap client and what they accept.
See if it accepts an array of your BalDto Objects
Utilize const listOfBalDtos = object.keys(result).map(); to do your transformation
Make the request:
soap.createClient(url, function(err, client) {
client.addSoapHeader(AuthHeader);
client.BalTransfer(listOfBalDtos);
});
try something like this.

nodejs filter for mongodb data

I am using node and MongoDB for my project, here I need to set the filter on node script so that the data comes out from my MongoDB is filtered. But I do not understood how to use filter functionality on my script. It will be a filtered method, or I can use find method, or use loop
to filter the data in my MongoDB using node js script.
I am not exactly getting the idea.
What I want to do?
1) I had sent a set off a question from my MongoDB to the frontend.
2) Questions Data is coming from the front end and saved via using node js API. I have to save questionId, a score.
3) Next time when I have to send the data I NEED FILTER HERE so that data I have sent previously not sent again.
Id will generate automatically in MongoDB. So I have not mention id here.
This is my question schema
title: {type: String, required:true},
options: {type: Array, required:true},
result: {type: Array, required:true},
here i am storing my questionid, score values coming from frontend.
This is my question id, score save schema
child: {
quiz: {
questionId:{type:String},
score:{type:Number},
time:{type:String}
}
}
This is my node js API filter. I am trying this but I am not sure this is right or wrong. Please help me to fix this proble.m
this.childfilter = function(req, res, next) {
async.waterfall ([
function(callback) {
try {
var query = { 'child.quiz.score': 1 };
var projection = '';
childinfo.find(query,function(err,data) {
if(err) return next(err);
res.send(data);
callback(null, data)
});
}
catch(err) {
console.log(err);
return next(err);
}
},
function(callback, data) {
try {
var childq = new childquestion();
var query = { 'data.child.quiz.questionId' : childq._id };
var projection = 'id title options result';
childquestion.find(query,projection)
.skip()
.exec(function(err,data){
if (err) return next(err);
res.send(data);
});
}
catch(err) {
console.log('Error While Saving the result ' +err);
return next(err);
}
}
]);
}

Async confusion in nodejs function

I always have multiple operations in one route or endpoint. Take an example below, when a user deletes an item, I want the related file be deleted in s3 too besides deleting related collection from the database.
So is the code below ok? Does it matter if I put the first function (delete file from s3) inside the DeleteItem function?
router.post('/item/delete', function(req, res) {
if(req.body.dlt_item){
var tempArray = [];
tempArray.push({"Key":req.body.dlt_item});
s3Bucket.deleteObjects({
Bucket: 'myS3',
Delete: {
Objects: req.body.dlt_item
}
}, function(err, data) {
if (err)
return console.log(err);
});
}
Item.DeleteItem(req.body.item_id, function(err,result){
if(err){console.log(err)}
res.send({result:1});
})
});
You should organise your code like this. This will ensure that s3 deletion will start only when mongodb deletion has finished.
In your code both things happen simultaneously. this may cause issue in some cases.
If one fails and other succeeds then there will be trouble. Suppose s3 files get deleted successfully and mongo deletion fails. Then you will have many references to non existing resources.
router.post('/item/delete', function(req, res) {
if(req.body.dlt_item){
var tempArray = [];
tempArray.push({"Key":req.body.dlt_item});
Item.DeleteItem(req.body.item_id, function(err,result){
if(err)
{
console.log(err)
res.send(err);
}
else
{
//deletion from mongodb is succesful now delete from s3
s3Bucket.deleteObjects({
Bucket: 'myS3',
Delete: {
Objects: req.body.dlt_item
}
},function(err, data) {
if (err)
{
// deletion from s3 failed you should handle this case
res.send({result:1});
return console.log(err);
}
else
{
// successful deletion from both s3 and mongo.
// If you do not want to wait for this then send the response before this function.
res.send({result:1});
}
});
}
})
});

Access API endpoints in MEANjs from server controller

so i have this problem i am working on 'following' feature in my application. What's important, i have two models:
Follows and Notifications
When I hit follow button in front-end I run function from follow.client.controller.js which POSTs to API endpoint /api/follows which corresponds to follow.server.controller.js and then update action on Follows model is performed - easy. AFAIK thats how it works (and it works for me).
But in follows.server.controller.js I want also invoke post to API endpoint at /api/notifications which corresponds to notifications.server.controller.js but I can't find a proper way to do that. Any help will be appreciated.
I don't want another call from front-end to add notification because it should be automatic = if user starts following someone, information is saved in both models at once.
You can add middleware in your server route.
app.route('/api/follows')
.post(notification.firstFunction, follows.secondFunction);
And now add 2 methods in your contollers. First makes the call to db and add's some result's data to request object which will be forwarded to second method.
exports.firstFunction= function(req, res, next) {
Notification.doSometing({
}).exec(function(err, result) {
if (err) return next(err);
req.yourValueToPassForward = result
next(); // <-- important
});
};
exports.secondFunction= function(req, res) {
//...
};
Or you can make few database calls in one api method, joining this calls with promises. Example:
var promise = Meetups.find({ tags: 'javascript' }).select('_id').exec();
promise.then(function (meetups) {
var ids = meetups.map(function (m) {
return m._id;
});
return People.find({ meetups: { $in: ids }).exec();
}).then(function (people) {
if (people.length < 10000) {
throw new Error('Too few people!!!');
} else {
throw new Error('Still need more people!!!');
}
}).then(null, function (err) {
assert.ok(err instanceof Error);
});

Can't list documents in mongodb collection using MongoClient in node.js

I can connect to my database from node.js using the MongoClient. I amb able to write, update and remove docs from a collection. But I am not able to retrieve data from it. This is my code:
var mongoClient=require('mongodb').MongoClient;
var mongoDbObj;
mongoClient.connect('mongodb://127.0.0.1:27017/trendoa', function(err, db){
if(err){
console.log(err);
}else{
global.db = db;
};
var col = global.db.collection('twitter_accounts_mon');
// create
var doc1 = {'hola':'sushi'};
col.insert(doc1, function(err, result) {
callback(err);
});
// update
col.update({hola:'jordi'}, {$set:{hola:'joan'}}, {w:1}, function(err, result) {});
// delete
col.remove({hola:'jordi'}, function(err, result) {
callback(err);
});
// read
col.find().toArray(function(err, docs) {
console.log(docs);
});
What I'm trying to do in the last lines of code is to get all the documents using find() but it doesn't return any results.
Through the mongo shell, using this command I get data on screen:
db.twitter_accounts_mon.find()
I don't know what I'm doing wrong. Thanks!
the nodejs callbacks must nest, ie only search the collection once the db is open
mongoClient.connect('mongodb://127.0.0.1:27017/trendoa', function(err, db){
var col = db.collection('twitter_accounts_mon');
coll.find({}, function(err, cursor) {
cursor.toArray(function(err, data) {
// process the data array
}
}
}
According to the MongoDB documentation on the Node.js driver, the find method does not execute the actual query, it builds an instance of a cursor that you then use to retrieve data. thus, you need to handle the result of the query.
var entireCollectionArray = col.find().toArray(function(err, items) {});
entireCollectionArray.forEach(function (element) {
console.log(element);
});

Categories

Resources