Search Value Firebase Node.js - node.js

I am trying to access a key with unknown parent as :
var ref = admin.database().ref("user_contacts/{pushId}").child(event.data.ref.parent.key);
ref.once("value", function(querySnapshot) {
var qVal = querySnapshot.val();
console.log("Query Value:", qVal);
});
Snapshot always return null, data exists for this key under multiple.
{pushId} //push ids are unknown here.
I also tried this:
var ref = admin.database().ref("user_contacts/{pushId}").orderByChild(snapshot.ref.parent.key);
ref.once("value", function(querySnapshot) {
var qVal = querySnapshot.val();
console.log("Query Value:", qVal);
});
but same response.
Is there any else way to achieve this? Or any body here can suggest an improvement in my method? I am just trying to search a key in the database.

Related

I want to return data from dynamodb when the key matches

**I want to return the data key values but it is not working. Please help me. The main concept of this method is when this is invoke dal is the keyword and it fetches that key values from the dynamodb. For that i used global also but not updating that global variable also.
I tried returning the value from the callback, as well as assigning the result to a local variable inside the function and returning that one, but none of those ways actually return the response (they all return undefined or whatever the initial value of the variable result is).**
function getLocation(){
let a=[];
const documentClient = new AWSS.DynamoDB.DocumentClient({region:"us-east-2"});
const params = {
TableName : "ProductLocation1",
Key :{
Product_Name : 'dal'
}
};
documentClient.get(params,(err,data)=>{
if(err){
console.log('error is',err);
}
console.log('data is : ',data);
global.a=Object.keys(data);
});
return global.a;
}
try {
const result = await documentClient.get(params).promise();
} catch (error) {
// handle error
}
You could get the result using the promise & await rather than the callback function. In this way, you don't need to store them in a local variable.

AutoIncrement of Multiple columns in indexeddb

Does any one know - how we can specify autoincrement for two columns in indexeddb.
I know - we can specify autoincremnt for one column while creating table like this -
var objectStore = thisDb.createObjectStore("note", { keyPath: "id", autoIncrement:true });
but not able to find how we can do the same for multiple columns. Also as far as i know - we cant get the value of autoincrement. The value will be autoincremented & added when we will insert the data. So if i can get the autoincrement value somehow, that would the solution too.
You cannot create two auto-incremented properties in a store. That feature is only available for the property defined as the key path.
You can easily get the auto-incremented value. The value is provided as the result of the put or add request that inserted a new object.
For example:
function addThing(db, thing) {
return new Promise((resolve, reject) => {
let id = undefined;
const transaction = db.transaction('things', 'readwrite');
const store = transaction.objectStore('things');
// wait to resolve the promise until the transaction is completed
// so that we do not prematurely pretend the operation succeeded. resolve
// to the value of the new id
transaction.oncomplete = event => resolve(id);
transaction.onerror = event => reject(event.target.error);
// store.add also works here
const request = store.put(thing);
// listen for the add event and grab the value of the new id
// that indexedDB generated and store it in the id variable
request.onsuccess = event => id = event.target.result;
});
}
async function doSomething() {
const something = {bar: 'baz'};
const db = await open(...);
const id = await addThing(db, something);
db.close();
something.id = id;
console.log(something);
}

Replace Multiple Documents in Cosmos DB using Store procedure

I had Fetch Multiple Documents. I had cast all the Documents to there respective data Models. After Updating properties of each Document, I need to save all the documents from a stored procedure.
I have Read the Documentation of stored procedure Collection in this the Method replaceDocument(documentLink, document, optionsopt, callbackopt) Required documentLink which I can not find after Casting.
I have tried this function but it did not work
function bulkReplace(docs) {
var collection = getContext().getCollection();
var collectionLink = collection.getSelfLink();
var count = 0;
if (!docs) throw new Error("The array is undefined or null.");
var docsLength = docs.length;
if (docsLength == 0) {
getContext().getResponse().setBody(0);
return;
}
tryCreate(docs[count], callback);
function tryCreate(doc, callback) {
var isAccepted = collection.replaceDocument(doc._self, doc, callback);
if (!isAccepted) getContext().getResponse().setBody(count);
}
function callback(err, doc, options) {
if (err) throw err;
count++;
if (count >= docsLength) {
getContext().getResponse().setBody(count);
} else {
tryCreate(docs[count], callback);
}
}
}
Exception details:
"Unable to Process Request","errorDetails":"The server encountered a
problem while processing your request, please try again
"technicalReason":"Type:Microsoft.Azure.Documents.DocumentClientException
Source:Microsoft.Azure.Documents.Client Message:Message:
{\"Errors\":[\"Encountered exception while executing Javascript.
Exception = Error: Invalid document link: \"undefined\".\r\nStack
trace: Error: Invalid document link: \"undefined\".\n at
validateDocumentLink
(bulkReplace.js:349:21)\natreplaceDocument(bulkReplace.js:780:17)\n
at tryCreate (bulkReplace.js:45:9)
I tested your code on my side and it works.
As we know, documents in azure document db has a few auto-generate fields including "_self". You do not need to make another query in stored procedure.You just need to ensure the documents in docs param you import contain the right "_self" field, otherwise the invalid document link exception occurs.
For example :
var doc = { "id": "2",
"name" : "ccc",
"_self": "dbs/duUuAA==/colls/duUuAPfBbAA=/docs/duUuAPfBbAAzAQAAAAAAAA==/",
}
I suggest you use console.log() to print the doc._self in your code to check the value of it.
Hope it helps you.

Return from then - nodejs

I am sort of new to NodeJS and I'm learning as I code but I can't wrap my head around Promise/then.
Here is the piece of code - I'm using a library function to Read database values.
var collection = 'Students';
var query = {};
query.name = 'name';
//readFromDatabse returns -{Function} a promise to return the document found, or null if not found
var temp = readFromDatabase(collection, query).then(function(studentData) {
var result = {
resultDetails: {
username: studentData.username,
password: studentData.password
}
};
return callback(null,resultDetails);
});
but when I read see the values in temp, it contains {"isFulfilled":false,"isRejected":false}!! how can I get the result details into temp?
You have to think of Promises as containers for values. readFromDatabase returns such a container, which might eventually hold the requested value unless the query fails. Your temp variable points to the container, but not the response. The properties isFullfilled and isRejected are attributes of the Promise telling you that it has neither been resolved with a value or rejected with an error.
To get to the response you have to use the then method. The function you register there will be called for you, when the query yields a result or an error.
var collection = 'Students';
var query = {};
query.name = 'name';
var temp = null;
readFromDatabase(collection, query).then(function(studentData) {
var result = {
resultDetails: {
username: studentData.username,
password: studentData.password
}
};
temp = result;
});
// temp is still null here

How to change the document using pre save in Mongoose

I am trying to assign the pre handler to the mongoose save event and encrypt the document before saving:
userShecma.pre('save', function(next) {
var self = {};
self.Key = this.password;;
self.EncriptedString = encrypt.encrypt(JSON.stringify(this), this.password);
self.user = this.user
self.decrypt = function() {
var user = JSON.parse(encrypt.decrypt(this.EncriptedString, this.Key));
for(var key in user) {
this[key] = user[key];
}
}
for(var key in this){
delete this[key];
}
for(var key in self){
this[key] = self[key];
}
console.log(this);
next(self);
});
I have tried a bunch of diffrent things, sometimes I get an error, sometimes it just doesnt change the document.
Let me know if you need any more info,
Ari
EDIT: Tried Benoir's Answer, I can't edit this.
I believe calling next(self) will make the next handler think that there was an error and not save the document.
You should just call next()
Look at http://mongoosejs.com/docs/middleware.html
under 'Error Handling'
I Figured It Out:
Benoir's Answer + You Cannot add or remove properties to/from the document unless they are defined in the Schema.

Resources