409 error conflict update, updating pouchDB doc - angularjs

I have a weird conflict with my pouchDB code trying to update a document in my database
code:
this.addToExistingUser = function (docId, key, value) {
usersDatabaseRemote
.get(docId)
.then(function (doc) {
doc[key] = value;
return usersDatabaseRemote.put(doc, docId, doc._rev);
})
.then(function () {
console.log('added field: ' + key + ' to doc ' + docId);
})
.catch(function (err) {
console.log("error from addToExistingUser:");
console.log(JSON.stringify(err));
});
}
where :
.factory('usersDatabaseRemote', [
'pouchDB',
function (pouchDB) {
'use strict';
var usersDatabaseRemote = pouchDB('https://id:pwd#id.cloudant.com/boardl_users');
return usersDatabaseRemote;
}
])
leads to :
{"status":409,"name":"conflict","message":"Document update conflict","error":true,"reason":"Document update conflict."}
But as you can see from the code I take the revision number rev from the remote document so I don't see why is there a problem with this.
Thanks

credit: #AlexisCôté
I was calling several times the async function that updates the remote doc
pouchDBservice.addToExistingUser(userr._id, 'weight',
pouchDBservice.addToExistingUser(userr._id, 'height', userHeight);
pouchDBservice.addToExistingUser(userr._id, 'technique', userTechnique);
and this was messing with the ._rev number.
So now I am doing all the parameters at the same time in an object :
pouchDBservice.addObjectToExistingUser(userr._id, objectToAdd);
with :
this.addObjectToExistingUser = function (docId, obj) {
usersDatabaseRemote
.get(docId)
.then(function (doc) {
for (var key in obj) {
if (!obj.hasOwnProperty(key)) continue;
console.log(key, obj[key])
doc[key] = obj[key];
}
return usersDatabaseRemote.put(doc);
})
.then(function () {
console.log('addObjectToExistingUser added object: ' + JSON.stringify(obj) + ' to doc ' + docId);
})
.catch(function (err) {
console.log("error from addObjectToExistingUser:");
console.log(JSON.stringify(err));
});
};

Related

throw new ERR_INVALID_ARG_TYPE('chunk',['string','Buffer'],chunk);TypeError[ERR_INVALID_ARG_TYPE]:The "chunk" arg must be type string or Buffer

I am trying to get the contents of a .json file using a node js service into an angularjs method. But am getting following error:
_http_outgoing.js:700
throw new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer'], chunk);
^
TypeError [ERR_INVALID_ARG_TYPE]: The "chunk" argument must be one of type string or Buffer. Received type object
at ServerResponse.end (_http_outgoing.js:700:13)
here are the corresponding code fragments...
angular controller: the commented lines are all of those which i have tried and failed with.
var currentProcess = "process_1cA";
$scope.storestats = [];
var resAss = $resource('/procs/getstorestats');
var stats = resAss.get({
process: currentProcess,
date: date.getFullYear() + "" + m + "" + d
});
stats.$promise.then(function(response) {
if (response != undefined) {
// var r = JSON.parse(response);
//$scope.storestats.push(r);
//$scope.storestats.push(r);
//var r = JSON.parse(response);
$scope.storestats.push(response);
//angular.forEach(r, function(value, key) {
// $scope.storestats.push({key : value});
//});
}
});
NODEJs service:
httpApp.get('/procs/getstorestats', function(req, res, next) {
try {
fs.readFile(cfg.routestatspath + "storestats-"+req.query.process + "-" + req.query.date + ".json", function (err, data) {
var msgs1 = JSON.parse(data);
//var r = data.toString('utf8');
var msgs2 = JSON.stringify(msgs1);
console.log(msgs1);
res.end(msgs1);
});
}
catch (err) {
res.end(err.toString());
}});
P.S: The commented out lines are those which i have tried out with and failed. Also, the commented lines in the node service code snippet, give no error, and when logged show it correctly, but the data when in response of the controllers is blank.
I'm guessing a bit here, but I think you just need to change res.end() to res.send() in your Node code. The "end" method is used when you are streaming chunks of data and then you call end() when you're all done. The "send" method is for sending a response in one go and letting Node handle the streaming.
Also, be sure you are sending a string back!
httpApp.get('/procs/getstorestats', function(req, res, next) {
try {
fs.readFile(cfg.routestatspath + "storestats-"+req.query.process + "-" + req.query.date + ".json", function (err, data) {
var msgs1 = JSON.parse(data);
//var r = data.toString('utf8');
var msgs2 = JSON.stringify(msgs1);
console.log(msgs1);
res.send(msgs2); // NOTE THE CHANGE to `msg2` (the string version)
});
}
catch (err) {
res.send(err.toString()); // NOTE THE CHANGE
}
});
I had a similar error. It was because I was passing process.pid to res.end(). It worked when I changed process.pid to string
res.end(process.pid.toString());
Figured it out. 2 small changes were needed.. One in the controller, which was to use a "$resource.query" instead of "$resource.get". And in the service, as #jakarella said, had to use the stringified part in the .end();
Controller:
var resAss = $resource('/procs/getstorestats');
var stats = resAss.query({process: currentProcess, date: date.getFullYear() + "" + m + "" + d});
stats.$promise.then(function (response) {
$scope.storestats.push(response);
}
Node Service:
httpApp.get('/procs/getstorestats', function(req, res, next) {
try {
fs.readFile(cfg.routestatspath + "storestats-"+req.query.process + "-" + req.query.date + ".json", function (err, data) {
var msgs1 = JSON.parse(data);
var msgs2 = JSON.stringify(msgs1);
console.log(msgs2);
res.end(msgs2);
});
}
If you are using 'request-promise' library set the json
var options = {
uri: 'https://api.github.com/user/repos',
qs: {
access_token: 'xxxxx xxxxx'
},
headers: {
'User-Agent': 'Request-Promise'
},
json: true // Automatically parses the JSON string in the response
};
rp(options)
.then(function (repos) {
})
.catch(function (err) {
});
Thank you user6184932, it work
try {
await insertNewDocument(fileNameDB, taskId);
res.end(process.pid.toString());
} catch (error) {
console.log("error ocurred", error);
res.send({
"code": 400,
"failed": "error ocurred"
})
}
in mysql2 the reason for the error is the sql word , sql is a query :
const sql = select * from tableName
pool.executeQuery({
sql,
name: 'Error list for given SRC ID',
values: [],
errorMsg: 'Error occurred on fetching '
})
.then(data => {
res.status(200).json({ data })
})
.catch(err => {
console.log('\n \n == db , icorp fetching erro ====> : ', err.message, '\n \n')
})
I got the error using Node v12 (12.14.1).
Uncaught TypeError [ERR_INVALID_ARG_TYPE]: The "chunk" argument must be one of type string or Buffer. Received type number
Sample code for context.
const { Readable } = require('stream')
Readable.from(Buffer.from(base64content, 'base64'))
.pipe( ... )
Solution (for my case), was upgrading to Node v14 (14.17.3). e.g.
nvm use 14
nvm

Node.js mssql data input layer with connection pool

This question relates to a Node.js mssql API.
I've recently updated my code to use a SQL.ConnectionPool instead of sql.connect which when combined with an async / await function allowed me to get around connection.close() errors.
In my previous (OLD) executeQuery function, I was able to pass an array which I could push values into to use with "request.input(name, value)"
Function call example:
app.get('/api/route/:id', function (req, res) {
var id = req.params.id;
let x = []
if (id != null && id != NaN) {
x.push({
Name: 'id', Value: id
})
var query = `SELECT * from [Table] where ID = #id`
executeQuery(res, query, arr);
} else {
res.send(500)
}
})
OLD Function:
var executeQuery = function (res, query, arr) {
sql.connect(dbConfig, function (err) {
if (err) {
console.log('Error while connecting to the database: ' + err)
res.send(err)
} else {
// Create the request object
var request = new sql.Request();
if (arr != null) {
if (arr.length > 0) {
for (var obj of arr) {
request.input(obj.Name, obj.Value)
}
}
}
request.query(query, function (err, rs) {
if (err) {
sql.close();
console.log('Error while querying the database : ' + err);
res.send(err);
} else {
sql.close();
console.log(rs)
res.send(rs)
}
})
}
})
}
NEW Function:
var executeQuery = async function(res, query, arr){
const pool = new sql.ConnectionPool(dbConfig);
pool.on('error', err => {
console.log('sql errors ', err);
});
try {
await pool.connect();
let result = await pool.request().query(query);
console.log('success')
res.send(result);
return {success: result};
} catch (err) {
console.log('error')
console.log(err)
res.send(err);
return {err: err};
} finally {
pool.close();
}
}
Question
How do I go about achieving the same request.input process with a ConnectionPool as I did with my previous function ( like the below )
var request = new sql.Request();
if (arr != null) {
if (arr.length > 0) {
for (var obj of arr) {
request.input(obj.Name, obj.Value)
}
}
}
Thank you.

Delete document from watson rank and retrieve

I've created a watson rank and retrieve collection. I was able to add a document and I can search it, but it was a test document. How do I delete it?
This is what I want to delete:
// add a document
var doc = { id : 1234, title_t : 'Hello', text_field_s: 'some text' };
solrClient.add(doc, function(err) {
if(err) {
console.log('Error indexing document: ' + err);
} else {
console.log('Indexed a document.');
solrClient.commit(function(err) {
if(err) {
console.log('Error committing change: ' + err);
} else {
console.log('Successfully commited changes.');
}
});
}
});
solrClient.deleteByID(1234, function(err) {
solrClient.commit(function (err) {
// obviously add error-handling
});
});

how to get excel cell data changed event using new api or Excel object in office.js

I am trying to find out how to get cell changed event using the Excel object
Excel.run(function (ctx) {
}
in office 2016.
is the context used by Office.context.document is same as context used in run function
found the answer for this.
Binding concept used earlier can be used now also as shown in the example https://github.com/OfficeDev/office-js-docs/blob/master/reference/excel/bindingcollection.md
(function () {
// Create myTable
Excel.run(function (ctx) {
var table = ctx.workbook.tables.add("Sheet1!A1:C4", true);
table.name = "myTable";
return ctx.sync().then(function () {
console.log("MyTable is Created!");
//Create a new table binding for myTable
Office.context.document.bindings.addFromNamedItemAsync("myTable", Office.CoercionType.Table, { id: "myBinding" }, function (asyncResult) {
if (asyncResult.status == "failed") {
console.log("Action failed with error: " + asyncResult.error.message);
}
else {
// If successful, add the event handler to the table binding.
Office.select("bindings#myBinding").addHandlerAsync(Office.EventType.BindingDataChanged, onBindingDataChanged);
}
});
})
.catch(function (error) {
console.log(JSON.stringify(error));
});
});
// When data in the table is changed, this event is triggered.
function onBindingDataChanged(eventArgs) {
Excel.run(function (ctx) {
// Highlight the table in orange to indicate data changed.
var fill = ctx.workbook.tables.getItem("myTable").getDataBodyRange().format.fill;
fill.load("color");
return ctx.sync().then(function () {
if (fill.color != "Orange") {
ctx.workbook.bindings.getItem(eventArgs.binding.id).getTable().getDataBodyRange().format.fill.color = "Orange";
console.log("The value in this table got changed!");
}
else
})
.then(ctx.sync)
.catch(function (error) {
console.log(JSON.stringify(error));
});
});
}
})();

Angular and Mongoose - Cant access some user value. Others appear fine

Im creating a comments system and im trying to add values to the view such as the text, userName, timePosted and userProfileImageURL but the only one that wont appear is the userProfileImageURL.
I think the problem is with the controller function but it could be somewhere else altogether.
/**
* Comment middleware
*/
exports.commentByID = function (req, res, next, id) {
Comment.findById(id).populate('user', 'displayName').exec(function (err, comment) {
if (err) return next(err);
if (!comment) return next(new Error('Failed to load Comment ' + id));
req.comment = comment;
next();
});
};
or Here Possibly
/**
* List of Comments
*/
exports.list = function (req, res) {
var id = req.dealId;
console.log('Log - ' + id);
Comment.find( )
.sort('-created')
.populate('user', 'displayName')
.exec(function (err, comments) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
res.jsonp(comments);
}
});
};
What does the 'user' and 'displayName' parameter in this function do?
Can i add the 'userProfileImageURL' also to the returned data somehow?
Im using the profileImageURL value like this. display name is showing but not the profileImageURL
<img ng-src="{{post.user.profileImageURL}}" alt="{{post.user.displayName}}" />
/**
* List of Comments
*/
exports.list = function (req, res) {
var id = req.dealId;
console.log('Log - ' + id);
Comment.find( )
.sort('-created')
.populate('user')
.exec(function (err, comments) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
res.jsonp(comments);
}
});
};
Just have to delete the displayName parameter and it will send the whole user object.

Resources