Replace and update IDs using JavaScript stored procedure - javascript

Background:
I need to create a stored procedure in JavaScript (within CosmosDB) where: For every Feedback document, replace/update Feedback.id with new id
var NewID = "5678"
{
"Feedbacks" : [
{
"id": "1234"
}
{
"id": "1234"
}
]
}
This is what I am doing:
I have created a function called UpdateID and set the parameters to OldID and NewID. I am saying iterate through the document, and for every OldID value,, replace with the NewID. I am moreso familiar with Python so this is a bit different for me and I am not sure this is the correct approach.
For every iteration in doc.Feedbacks:
function UpdateID(OldID, NewID) {
if (Feedbacks.id = "OldID")
}
Any suggestion will be helpful

There are a handful of ways to write the javascript, but here's one way that should get on the right track:
function UpdateID(oldID, newID) {
//get just the records that need updating
var isAccepted = __.filter(
function(doc) {
return doc.Feedbacks && doc.Feedbacks.findIndex(function(feedback){
return feedback.id == oldID
}) > -1;
},
function (err, feed, options) {
if (err) throw err;
// Check the feed and if empty, set the body to 'no docs found'
if (!feed || !feed.length) {
var response = getContext().getResponse();
response.setBody('no docs found');
}
else {
//update the documents that have the old id
UpdateDoc(oldID, newID, feed)
}
});
if (!isAccepted) throw new Error('The query was not accepted by the server.');
}
//function based on https://stackoverflow.com/questions/36009939/documentdb-updating-multiple-documents-fails
function UpdateDoc(oldID, newID, documents) {
console.log("updating " + documents.length + " docs")
if (documents.length > 0) {
var document = documents[0];
// DocumentDB supports optimistic concurrency control via HTTP ETag.
var requestOptions = { etag: document._etag};
document.Feedbacks = document.Feedbacks.map(function(feedback){
if(feedback.id === oldID) {
feedback.id = newID;
}
return feedback;
});
// Update the document.
var isAccepted = __.replaceDocument(document._self, document, requestOptions, function(err, updatedDocument, responseOptions) {
if (err) {
responseBody.error = err;
throw err;
}
});
// If we hit execution bounds - throw an exception.
if (!isAccepted) {
responseBody.log += "Update not accepted";
response.setBody(responseBody);
}
else {
documents.shift();
if(documents.length > 0){
UpdateDoc(oldID, newID, documents);
}
}
}
}

Related

Compare data in two databases in Node.js and MongoDB

I have created two databases (1-btech2014 & 2-btechre2014) in one server in Node.js and MongoDB.
I want to compare data of btech2014 with btechre2014. If they are the same, then I should be able to get data in output of btech2014. Else I should return a message. How to compare the two databases on same server?
The data contains:
name;
id (unique for all);
cpi.
Here is my code:
var findData = function(db, callback) {
var cursor = db.collection('btech2014').find();//data from our processing task
var cursor2 = db.collection('btechre2014').find();//data form replica
cursor.each(function(err, doc) {
/*cursor2.each(function(err, doc2) {
assert.equal(err, null);
if (doc != null && doc == doc2) {
console.log(doc);
data[i]=doc;
i++;
count++;
} else {
callback();
}
})*/
assert.equal(err, null);
if (doc != null ) {
console.log(doc);
data[i]=doc;
i++;
} else {
callback();
}
});
/*var cursor = btech2014.find().forEach(function(doc1){
var cursor2 = btechre2014.findOne({name: doc1.name});
//var flag = JSON.stringify(doc1)==JSON.stringify(doc2);
if(JSON.stringify(doc1)==JSON.stringify(doc2)){
console.log(doc1);
}
else{
console.log('system on attack!!');
}
});*/
/*if(count != 5){ //total 5 entries to be checked
console.log('there is an attack on the system!');
}*/
}
Did you tried to convert both in md5 and compare?
I dont know how much rows you have, maybe works...

How to scan dynamoDB in lambda?

so I have a table of 10 items, each item has about 5 keys (name,experience,level, etc). Now, I want to scan that table, get each item as an object and add it to an array and then JSON stringify that array and return it.
I just need help with the scanning code and getting all items and putting it into an array.
Here's my code I have currently.
var dynamodb = new AWS.DynamoDB.DocumentClient();
exports.handler = function(event, context, callback)
{
var returnArray = {
"cards": {}
}
getCards();
function getCards() {//Not sure how to write this function
var params = {
TableName : "toBeApprovedTable",
Key: {//not sure what to put here, since I want all items, and not searching through keys.
},
};
dynamodb.scan(params,function(err,data)
{
if(err)
{
console.log("error in scanning");
}
else
{
console.log("scanning success!");
//Not sure what to do here.
}
});
}
};
I figured it out after scrapping through Google + AWS docs.
Here is how to scan a table for all elements in the table. My return is a map, which contains an array of elements. Each element is a map of my object.
exports.handler = function(event, context, callback)
{
var returnArray = {
"cardsToBeApproved":[]
};
getCards();
function getCards() {//Not sure how to write this function
var params = {
TableName : "toBeApprovedTable"
};
dynamodb.scan(params,onScan);
}
function onScan(err,data)
{
if(err)
{
console.log("unable to scan table");
}
else
{
console.log("scan succeeded");
data.Items.forEach(function(card)
{
console.log("my card name is " + card.name);
var cardStringified = JSON.stringify(card);
returnArray.cards.push(card);
});
callback(null,JSON.stringify(returnArray));
}
}
};

Storing value to indexedDB if it is not defined

I'm trying to check if there is a record of 'uid' in indexed db from a service worker. If it's not defined, I need to add a value to it.
This is my code, I already tried in some ways that I found around other questions and sites, but none worked.
function checkUid() {
console.log('checking uid...');
var request = indexedDB.open('db',1);
request.onsuccess = function(event) {
var db = event.target.result;
var store = db.createObjectStore('Users', {keyPath:"users"});
var transaction = event.target.transaction;
db.transaction( '' ).objectStore( '' ).get( 'uid' ).onsuccess =
function(uid)
{
if (uid) {
console.log('uid found!');
console.log(uid);
console.log('uid end');
} else {
console.log('not found!');
db.transaction( '' ).objectStore( '' ).set( 'uid', 'aaaaa' );
console.log('uid end');
}
}
}
How can I do this?
This code opens the database with the name example, creates the object store called users if needed, gets the object with the key x123 from that store, and creates the object if it doesn't already exist.
function checkUid() {
let openRequest = indexedDB.open("example")
openRequest.onupgradeneeded = () => {
console.log("update needed")
openRequest.result.createObjectStore("users")
}
openRequest.onsuccess = () => {
console.log("opened database")
let store = openRequest.result.transaction("users", "readwrite").objectStore("users")
let uid = "x123"
let getRequest = store.get(uid)
getRequest.onsuccess = () => {
let result = getRequest.result
if (result) {
console.log("found:", result)
} else {
console.log("not found")
store.add("aaaaa", uid)
}
}
}
}
Use put() instead of set(), it will update the entry, or create one if it doesn't exist.
https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore/put

Async write after select Pouchdb

I'm trying to check if an element exist before inserting it in my bdd.
I have to do this in order to (in the future) modify this existing element.
I'm using PouchDb and PouchDb-find with Node 6.9.1.
Actually I'm doing this:
for(var i = 0; i < 10;i++ ){
(function(_count, _pdb){
var count = _count;
var db = _pdb;
db.find({
selector: {numeroCandidat: parseInt(results[count].no_apb)}
}).then((result) => {
if(result.docs.length != 0){
console.log("l'étudiant existe");
}else{
console.log("l'étudiant n'existe pas");
var etudiant = {
"numeroCandidat": results[count].no_apb,
"nom": results[count].nom,
"numeroGroupe": "gr" + results[count].groupe,
"filiere": results[count].libelle,
};
db.post(etudiant).then((response) =>{
// handle response
console.log("STUDENT CREATED");
}).catch(function (err) {
console.log(err);
});
}
}).catch(function (err) {
});
})(i, this.pdb);
};
But the problem is : Due to the asynchronous version of my select query... if an element exists two times it appends that the second select occurred BEFORE the insertion of the first element, and I have this element two times in my database. I don't know how to deal with this one.
SO.. I'v found a workaround !
Simply create a function that I call recursivly after writting into my database.
Goodbye for loop.
var createStudents = function(_count, _pdb, _students){
if(_count >= 10) return;
console.log(_count);
var count = _count;
var db = _pdb;
var students = _students.slice(0);
db.find({
selector: {numeroCandidat: parseInt(students[count].no_apb)}
}).then((result) => {
if(result.docs.length != 0){
console.log("l'étudiant existe");
createStudents(++count,db,results);
}else{
var etudiant = {
"numeroCandidat": students[count].no_apb,
"nom": students[count].nom,
"numeroGroupe": "gr" + students[count].groupe,
"filiere": students[count].libelle,
"etudiantComms": [
{"commentaire": students[count].commentaire}
]
};
db.post(etudiant).then((response) =>{
// handle response
console.log("STUDENT CREATED");
createStudents(++count,db,results);
}).catch(function (err) {
console.log(err);
});
}
}).catch(function (err) {
});
}
createStudents(0,this.pdb,results);

Push new field and value to json array object in node.js

I'm new to node.js. I need to display Name in jqgrid, but I stored only id of one document into another document.
Example
I have 2 documents like Student master and student mark document. I have to display mark details in jqgrid. In mark document I stored student id instead of name. How do I fetch the name and send a new object to jqgrid?
My code is as follows:
exports.getAllstudentsmark = function(req, callback)
{
studentsmarks.find(function(error, studentsmarks_collection) {
if( error ) callback(error)
else {
studentsmarks_collection.toArray(function(error, results) {
if( error ) callback(error)
else {
newresult = results;
for(i=0;i<results.length;i++)
{
newresult[i]['studentname'] = getStudentName(results[i].studentid);
}
console.log(newresult);
callback(null, newresult)}
});
}
});
}
var getstudentObjectId = function(id)
{
return student.db.bson_serializer.ObjectID.createFromHexString(id);
}
var getStudentName = function(id)
{
student.findOne({_id: getstudentObjectId (id)}, function(e, o){
console.log(o.name);
return o.name;
});
}
newresult[i]['studentname'] is always getting undefined. But if I log into getStudentName function I can get answer into getStudentName function.
My callback function is only getting this problem. How to resolve and get my result in an easy way. Please help any one.
try this inside your for loop
newresult.push({'studentname': getStudentName(results[i].studentid) });
exlpanation:
by the time you access newresult[i] it doesn't exist, so accessing studentname field of it is impossible
Your problem here is that you are not setting the name of the user into the array, but the return value of student.findOne, since this is an asynchronous method. Maybe try this thing
exports.getAllstudentsmark = function(req, callback)
{
studentsmarks.find(function(error, studentsmarks_collection) {
if( error ) callback(error)
else {
studentsmarks_collection.toArray(function(error, results) {
if( error ) callback(error)
else {
newresult = [];
for(i=0;i<results.length;i++)
{
getStudentName(results[i].studentid, function (studentName) {
newresult.push({studentname: studentName});
})
}
console.log(newresult);
callback(null, newresult)}
});
}
});
}
var getstudentObjectId = function(id)
{
return student.db.bson_serializer.ObjectID.createFromHexString(id);
}
var getStudentName = function(id, callback)
{
student.findOne({_id: getstudentObjectId (id)}, function(e, o){
console.log(o.name);
callback(o.name);
});
}
I hope it helps

Categories