How to store callback in node js - javascript

function getChild2 (user, userid, level, callback) {
User.find({ 'parentId': new mongoose.Types.ObjectId(userid), 'active': true },
{ "_id": true, "firstName": true,"lastName": true,"userId": true,"rightLeg": true,"leftLeg": true, "userName": true, "children": true, "activePackage": true, "type": true, "styleClass": true, "expanded": true }).
sort({ 'created': -1 }).exec(function (err, users) {
if (err) {
console1.error('Error:User:Read: ' + errorHandler.getErrorMessage(err));
} else {
console1.log('Log:User:Read: user network response ' + JSON.stringify(users));
user.children.push(users);
users.forEach(function (val, i) {
console.log('getchild2 ' + val._id);
getChild2(val, val._id, level+1, null);
});
if (users.length === 0)
{
callback(user);
}
}
});
I need to use the callback when users.length === 0 but on my iteration I am making the callback as null i.e at the end of loop callback is becoming null,then it says the error callback is not a function.Then I thought of storing the callback function initially in a variable.
if (callback !== null) {
toCall = callback;
}
then...
if (users.length === 0 ) {
toCall(users);
}
Now it says toCall is not a function.Can anyone please help me to solve this.Thanks.

Related

Fail while replicating data from PouchDb to CouchDb

My Code
thats is a short version of my current code.:
['tableA', 'tableB', 'tableC'].forEach(name => {
let local = new PouchDB(name, { auto_compaction: true })
let server = new PouchDB(serverUrl + name)
var filtro = {
include_docs: true,
filter: 'replication/by_dispositivo',
query_params: { 'dispositivo_id': obj.deviceId }
}
local.replicate.from(server, filtro).on('complete', report => {
var sync = local.sync(server, {
live: true,
retry: true,
...filtro
})
})
})
I'm trying to do a live replication, but for some reason, that doesn't replicate the local data to the server, strangely, PouchDb didn't throw any exception.
Inspecting the Network tab on Dev Tools, I can see te follow request.:
URL: ${serverUrl}/{name}/_revs_diff
Response: {
"4b0ea507-cd88-4998-baf0-01629b50516b": {
"missing": [
"2-2133d30de8d44ebd958cee2b68726ffb"
],
"possible_ancestors": [
"1-39904a7e55b1cb266c840a2acf34fdc2"
]
}
}
Ok, PouchDb detected that something is missing in the server and must be replicated.
Auditing the Sync
Searching for a hint about what is happening, I modified my code to log the complete and error events.:
['tableA', 'tableB', 'tableC'].forEach(name => {
let local = new PouchDB(name, { auto_compaction: true })
let server = new PouchDB(serverUrl + name)
let filtro = {
include_docs: true,
filter: 'replication/by_dispositivo',
query_params: { 'dispositivo_id': obj.deviceId }
}
local.replicate.from(server, filtro).on('complete', report => {
let sync = local.sync(server, {
live: true,
retry: true,
...filtro
})
sync.on('error', (error) => {
console.error(error)
console.error(JSON.stringify(error, null, 2))
}).on('complete', (result) => {
console.log(result)
console.log(JSON.stringify(result, null, 2))
})
window.setTimeout(function (evt) {
state.syncProcess[database].cancel()
}, 15000)
})
})
I didn't catch anything in the error event, and the complete event didn't show any errors as you can see bellow.
{
"push": {
"ok": true,
"start_time": "2018-04-06T15:00:42.266Z",
"docs_read": 0,
"docs_written": 0,
"doc_write_failures": 0,
"errors": [],
"status": "cancelled",
"end_time": "2018-04-06T15:00:42.266Z",
"last_seq": 0
},
"pull": {
"ok": true,
"start_time": "2018-04-06T15:00:26.422Z",
"docs_read": 0,
"docs_written": 0,
"doc_write_failures": 0,
"errors": [],
"last_seq": "17-g1AAAAJDeJyd0EsOgjAQBuAqJj52nkCPILGldCU3UaYzBA3CQl3rTfQmehO9CRZKAiaGiJtpMs18mX8SxtgodpBNdXbSMUKQZDpM4uxwTMxXP2Qwy_N8Fzsh25vGMILIA62QjU8pUrRNCVvGYW4qrCphUgoCfMVd_W2mTQoKaV1JjpWWIUcuu0qbQjp_pBKeUESLH1OlA1PZxTwGudb7EC1dQt5xH6vdrHYvtF6pSZK-4Oov7WG1Z53QUy56UnRK-LJK406-TxIAm8ruDdzts44",
"status": "cancelled",
"end_time": "2018-04-06T15:00:41.427Z"
}
}
Calling one time local to server replication manually
that is my second attempt to catch something usefull. I trying to audit the local.replicate.to method
['tableA', 'tableB', 'tableC'].forEach(name => {
let local = new PouchDB(name, { auto_compaction: true })
let server = new PouchDB(serverUrl + name)
let filtro = {
include_docs: true,
filter: 'replication/by_dispositivo',
query_params: { 'dispositivo_id': obj.deviceId }
}
local.replicate.from(server, filtro).on('complete', report => {
local.replicate.to(server, filtro).on('complete', report => {
console.log(report)
console.log(JSON.stringify(report, null, 2))
let sync = local.sync(server, {
live: true,
retry: true,
...filtro
})
}).on('error', (error) => {
console.error(error)
console.error(JSON.stringify(error, null, 2))
})
})
})
thats time complete event isn't fired and I catch a error, but that is too generic amd don't give any clues regarding whats is happening.
{
"result": {
"ok": false,
"start_time": "2018-04-06T15:07:19.105Z",
"docs_read": 1,
"docs_written": 0,
"doc_write_failures": 0,
"errors": [],
"status": "aborting",
"end_time": "2018-04-06T15:07:19.768Z",
"last_seq": 3
}
}
Putting local data to the server
thats is my last attempt.:
I'll query local and remote databases (in that particular case, I have only one document)
Copy fields from local doc to remote doc.
Dispatch the updated remote doc to the remote database
My Junk Code
var deviceId = ''
var listLocal = []
var listServer = []
getDeviceId().then(response => {
deviceId = response
return local.find({ selector: { dispositivo_id: deviceId } })
}).then(response => {
listLocal = response.docs
return server.find({ selector: { dispositivo_id: deviceId } })
}).then(response => {
listServer = response.docs
var tlocal = listLocal[0]
var tServer = listServer[0]
Object.keys(tServer).forEach(key => {
if (key.indexOf("_") !== 0) {
tServer[key] = undefined
}
})
Object.keys(tlocal).forEach(key => {
if (key.indexOf("_") !== 0) {
tServer[key] = tlocal[key]
}
})
return server.put(tServer).then(result => {
console.log(result)
console.log(JSON.stringify(result, null, 2))
}).catch(error => {
console.error(error)
console.error(JSON.stringify(error, null, 2))
})
})
The junk code worked as expected, and i received that response.:
{
"ok": true,
"id": "4b0ea507-cd88-4998-baf0-01629b50516b",
"rev": "2-d9363f28e53fdc145610f5ad3f75a043"
}
Additional Information
My design documents in the CouchDb
_design/replication
{
"_id": "_design/replication",
"_rev": "1-42df919aaee8ed3fb309bbda999ba03d",
"language": "javascript",
"filters": {
"by_dispositivo": "function(doc, req) {\r\n return doc._id === '_design/replication' || (doc.dispositivo_id === req.query.dispositivo_id && !doc._deleted)\r\n}",
"by_situacao_remote": "function(doc, req) {\r\n return [2, 3, 4, 5].indexOf(doc.situacao) !== -1 && !doc._deleted\r\n}"
}
}
_design/authorization
{
"_id": "_design/authorization",
"_rev": "9-64c4a22645d783c9089c95d69e9424ad",
"language": "javascript",
"validate_doc_update": "..."
}
authorization/validate_doc_update
function(newDoc, oldDoc, userCtx) {
var isAdmin = userCtx.roles.indexOf('_admin') !== -1 || userCtx.roles.indexOf('admin') !== -1;
if (!isAdmin) {
if (newDoc._deleted) {
if (oldDoc.dispositivo_id !== userCtx.name) {
throw({forbidden: "..." });
}
}
else {
if (!newDoc.dispositivo_id || !newDoc.dispositivo_id.trim())
throw({forbidden: "..." });
if (newDoc.dispositivo_id !== userCtx.name) {
throw({forbidden: "..." });
}
if (oldDoc && oldDoc.dispositivo_id !== userCtx.name) {
throw({forbidden: "..." });
}
var isRequired = function (prop, msg) {
var value = newDoc[prop];
if (!value)
throw({forbidden: '...' });
}
var isDate = function (prop, msg, allow_null) {
if (!allow_null)
isRequired(prop, msg)
var value = newDoc[prop];
if (value) {
var date = new Date(value);
var isDate = date !== "Invalid Date" && !isNaN(date);
if (!isDate) {
throw({forbidden: msg });
}
}
}
var isFloat = function (prop, msg, allow_null) {
if (!allow_null)
isRequired(prop, msg)
var value = newDoc[prop];
if (value) {
var numero = new Number(value);
if (!numero || isNaN(numero) || !isFinite(numero)) {
throw({forbidden: msg });
}
}
}
var isInteger = function (prop, msg, allow_null) {
isFloat(prop, msg, allow_null)
var value = newDoc[prop];
if (value) {
var numero = new Number(value);
var isInteger = Math.floor(numero) == numero;
if (!isInteger) {
throw({forbidden: msg });
}
}
}
isRequired("talao_id", "...");
isRequired("equipe_id", "...");
isInteger("situacao", '...');
isDate("data_envio", "...");
isDate("data_recebimento", "...", true);
isDate("data_decisao", "...", true);
isRequired("tipo_ocorrencia_codigo", "...");
isRequired("tipo_ocorrencia_descricao", "...");
isInteger("talao_codigo", "...");
isRequired("talao_descricao", "...");
isRequired("talao_solicitante", "...");
isRequired("talao_endereco", "...");
}
}
else if (!newDoc._deleted) {
if (!newDoc.dispositivo_id || !newDoc.dispositivo_id.trim())
throw({forbidden: "..." });
}
}
While analyzing the stack trace of the exception throw by local.replicate.to, I noticied that reason: promise.all is not a function.
So i googled for a while and found that topic Webpack: Promise is not a constructor. I just need to copy the workaround bellow to my webpack.config and everything worked like a charm.:
resolve: {
alias: {
'pouchdb-promise$': "pouchdb-promise/lib/index.js"
}
}

How to verify the particular value of the DB node of firebase database

I have a JSON structure as
{
"engagedUsers": {
"qwe": {
"agent_availability": true,
"conv_id": "parthengineer_qwe",
"emailId": "qwe#gmail.com",
"login_time": 1512644440,
"name": "qwe",
"uid": "adasfklsfjdskldgsgjgjkl"
},
"tt": {
"agent_availability": true,
"conv_id": "genesis_tt",
"emailId": "tt#gmail.com",
"login_time": 1512644440,
"name": "tt",
"uid": "adasfklsfjdskldgsgjgjkl"
}
}
}
I want to verify if the conv_id child is equal to parthengineer_qwe. I tried the below code but cannot got through it:
this.engagedRef = firebase.database().ref('engagedUsers');
this.engagedRef.orderByValue().once('value', function (snapshot) {
snapshot.forEach(function (data) {
// console.log("snapShot:" + data.child('conv_id').val());
if ((data.child('conv_id').val() == 'parthengineerqwe') && (existEngageduser !== 1)) {
existEngageduser = 1
// console.log("under haschild:" + existEngageduser);
}
if (existEngageduser == 1) {
isEngaged = true
// sessionStorage.isEngaged = isEngaged;
}
// console.log("isEngaged:" + isEngaged);
})
return isEngaged;
});
Please suggest a better way to achieve this as I know I am not going right way, I expect isEngaged variable as true
I'm still not sure what you want but why not have an external function to do it?
snapshot.forEach(function (data) {
if (isEngaged(data.val())) {
console.log(data.key, ' is engaged');
}
}
function isEngaged(userData) {
return (userData.conv_id === 'parthengineer_qwe') || false;
}

Sequelize - Bulk create from array

I have an array of items and need to create them to DB.
I need to check each insert if it success so insert to new array (results) the item + success = true as a json.
If not succeed to create - insert to the same array before (results) the item + success = false.
Here's the code:
create_cards: function (filter_id, is_filter, cards) {
var result = [];
var curr_card = null;
for (var card in cards) {
curr_card = this.create( {
filter_id: filter_id,
template: card.template,
state: card.state,
question_id: card.question_id || -1,
answers: card.answers || -1,
description: card.description || -1,
correct_answer: card.correct_answer || -1
}).then(function(card) {
result.push({card: JSON.stringify(card.dataValues), success: true})
},function(err) {
result.push({card: card.dataValues, success: false})
});
}
return results;
}
Now, 2 questions:
There is 'return result' after the loop is over, but i get empty array..
How should i do bulk create AND after each create, to make sure if the creation succeed?
How should i get the card in the error function? i get only 'err' as variable to the reject function.
Thanks!
create_cards: function(filter_id, is_filter, cards) {
var result = [];
var promises = cards.map(function(card) {
return this.create({
filter_id: filter_id,
template: card.template,
state: card.state,
question_id: card.question_id || -1,
answers: card.answers || -1,
description: card.description || -1,
correct_answer: card.correct_answer || -1
})
.then(function() {
result.push({
card: card,
success: true
});
})
.catch(function(err) {
result.push({
card: card,
success: false
});
return Promise.resolve();
});
});
return Promise.all(promises)
.then(function() {
return Promise.resolve(result);
});
}

mongoose findOneAndUpdate deletes nested vars

In my express/mongoose code when I update a nested var it deletes any other nested vars in the object I didn't update?
My schema:
var MySchema = new Schema({
active: { type: Boolean, required: true, default: true },
myvar: {
useDefault: { type: Boolean, required: true },
custom: { type: String },
default: { type: String }
}
});
My express middleware update function:
var updateData = req.body;
MySchema.findOneAndUpdate({ active: true }, updateData, function(err, myschema) {
if (err) throw err;
if (!myschema) { response(403, { success:false, message: "myschema not updated." }, res); }
// success
response(200, { success:true, message: "myschema updated." }, res);
});
The record initially look like this:
{
"myvar": {
"useDefault": true,
"custom": "some custom var",
"default": "some value"
}
}
When I submit an update to say the myvar.useDefault value the record ends up like this:
{
"myvar": {
"useDefault": false
}
}
Can anyone advise how to update only the targeted var and leave any other vars as they were?
The answer was to convert the response.body object to dot notation and pass that modified object to mongoose findOneAndUpdate. Thanks to #btkostner on Gitter for the answer and his toDot function. Here is the relevant bits of code:
function(req, res) {
// convert response to dot notation so objects retain other values
var dotData = toDot(req.body, '.');
MySchema.findOneAndUpdate({ active: true }, dotData, function(err, myschema) {
...
}
// author: #btcostner
function toDot (obj, div, pre) {
if (typeof obj !== 'object') {
throw new Error('toDot requires a valid object');
}
if (pre != null) {
pre = pre + div;
} else {
pre = '';
}
var iteration = {};
Object.keys(obj).forEach(function(key) {
if (_.isPlainObject(obj[key])) {
Object.assign(iteration, _this.toDot(obj[key], div, pre + key));
} else {
iteration[pre + key] = obj[key];
}
});
return iteration;
};
NOTE: I had to convert the toDot() function to ES5 for my project, here is the original ES6 version: github.com/elementary/houston/blob/master/src/lib/helpers/dotNotation.js

How to write query.equalTo multiple times in If condition (Parse)

I am just trying to check if user_id and comment_id is there in my database table and if they exists, then do x operation or else y operation.
And, I am taking this user_id and comment_id at the runtime from the user.
So how should I write my if condition using query.equalTo so that I can do my respective operations.
Below is the code of what I am trying to do.
Parse.Cloud.define("voteForComment", function(request, response)
{
var insertVote = Parse.Object.extend("trans_Votes");
var vote = new insertVote();
var query = new Parse.Query("trans_Votes");
if(query.equalTo("user_id",
{
__type: "Pointer",
className: "_User",
objectId: request.params.user_id
})) && (query.equalTo("comment_id",
{ __type: "Pointer",
className: "mst_Comment",
objectId: request.params.comment_id
})); // how to write this two equalTo queries..(its showing error)
{
query.find
({
success : function(rec)
{
X operation here
},
error : function(error)
{
response.error(error);
`}
});
}
else
{
y operation here
}
Thanks.
Your parentheses are a bit of a mess. Removing the equalTo() function calls from the if statement leaves us with this code wireframe:
if (...) && (...);
{
...
} else {
...
}
This is not going to work because of the syntax errors. We need to change it a bit:
if ((...) && (...))
{
...
} else {
...
}
Applying these changes to your code results in this:
if (query.equalTo("user_id", {
__type: "Pointer",
className: "_User",
objectId: request.params.user_id
}) && query.equalTo("comment_id", {
__type: "Pointer",
className: "mst_Comment",
objectId: request.params.comment_id
})) {
query.find({
success: function(rec) {
X operation here
},
error: function(error) {
response.error(error);
}
});
} else {
y operation here
}
That should work.

Categories

Resources