failed to access to a value in a json variable - node.js

I have some troubles with a variable after doing some mongodb processing
...................
console.log("MIP : value :" + value._id );
console.log("MIP : page id :" + value._id.id );
....................
The logs show this
MIP : value :{ id: '346593403645', _id: 57a868497e07fcf75f27009c, __v: 0 }
MIP : **page id :undefined**
I am not understanding why the value of value._id.id is undefined
Could you help please

Seems like You keep serialized data in value._id.
So try:
if(typeof value._id == 'string') {
value._id = JSON.parse(value._id);
}
also keep in mind that when You want to dump the variable don't concatenate variable with string.
just do:
console.log("MIP : value :", value);
it will show You the variable as is:
- if it's buffer so will show that it's buffer
- if object so will output it as object
Seems like Your json is malformed.
So use dirty-json package:
var dJSON = require('dirty-json');
dJSON
.parse(value._id)
.then(function (result) {
console.log(result.id);
});

Related

How to Update only passed value in mongodb using mongoose?

I have built an API that updates records in MongoDB using mongoose, but currently what happening is if I am passing only 4 field values in the JSON file of postman and try to update then all the values are updating with value null except that 4 fields which I had passed in JSON so can anyone help me how I can pass dynamic field and value that update only passed values of collection not all the fields of collection.
Passes JSON :
{
"preferance_id" : "60fe9ba1766d10d65c64083c",
"is_active": true,
"price_blur":true,
"affiliate_commission":27,
"language_code": "en"
}
Update call which I have passed in node js
transaction.update(PreferencesMasterName,
{ _id: new mongoose.Types.ObjectId(preferance_id) }, {
subscriptin_vat : subscriptin_vat,
popular_normal : popular_normal,
popular_crawled : popular_crawled,
price_blur : price_blur,
blur_rule : blur_rule,
affiliate_commission : affiliate_commission,
red_lock : red_lock,
automatic_dummy_price : automatic_dummy_price,
...
is_active: is_active
})
I want to pass dynamic field and values here instead of this because due to this other values are set will null value. So, can anyone have an idea how to do this?
You can do something like this:
const data = res.body; // should be an object that needs to updated
transaction.update({_id: PreferanceMasterName._id}, data, {new: true }, ( error, obj ) => {
if( error ) {
console.error( JSON.stringify( error ) );
}
console.log( obj );
});
In certain cases new doesn't work, you can use : { returnOriginal: false };
for more details, you can check this thread there are multiple ways you can do this.
Please check update how to use it.

Nodejs find array property value based on value of another property

I am having trouble finding the value of a property in an array based on the value of another property. I am trying to assign the variable x with the value of sensors.type when searching for a specific sensorID. For example in the table below if I have the value of the sensor ID (yellow box) I am trying to assign the value of the type (red box) to the variable x.
I load an array 'sensors' with data from a PostgreSQL database with the following code:
var sensors = [];
var pgp = require('pg-promise')(options);
var connection = "postgres://xxxxxxx:yyyyyyy#xxx.xxx.xxx.xxx/heatmap"
var db = pgp(connection);
getSensors();
setInterval(getSensors,10000)
function getSensors(){
var q = "select * from sensors order by id"
db.query(q)
.then(function (data) {
data.forEach((s)=>{
sensors[s.mac.trim()] = s
console.log(s)
})
}, function (reason) {
console.log(reason);
})
.catch(function (error) {
console.err("Query error, "+error);
});
}
when I run the command console.table(sensors) this is what I see ..
Also I can see details for each record with console.dir(sensors) ...
I have an input string which I parse to get the sensorId I want to search the array for and can verify it exists with a valid value via console.log output.
var sensorId = rawData.substring(6,18);
var sensorRecord = sensors[sensorId];
I cannot seem to find a way of searching the array for the sensorType and assigning the value of the associated 'type' from the array to a variable.
I thought the following would:
var sensorType = sensors[sensorId].type;
But it returns the following error:
Would appreciate any help and guidance.

How to update a collection document using multiple criteria

I have this document in collection "registosSRS":
{
"_id" : ObjectId("5a3a2b47d04b7e07f8a273dc"),
"sessao" : "5",
"valorRelacao" : "4.89",
"valorObjectivo" : "4.97",
"valorAbordagem" : "4.88",
"valorGeral" : "4.92",
"cliente_id" : "5a1407c8099ca208e48170a5",
"email" : "mgoncalves#psi.uminho.pt",
"data" : 1513761607431
}
and this document in collection sessao. I've created this document in another place, and set dadosSRS to {} because I want to later change this value. Is this possible to add this value without having created it?
"_id" : ObjectId("5a3a2b41d04b7e07f8a273db"),
"cliente" : ObjectId("5a1407c8099ca208e48170a5"),
"data" : 1513761601705,
"numero" : "5",
"dadosORS" : ObjectId("5a3a2b41d04b7e07f8a273da"),
"dadosSRS" : {
}
Then I'm looking in collection sessao for a client and number os session as in registosSRS, to add the registosSRS id.
mongoClient.collection('sessao', function(err,collection){
collection.update(
{cliente:result.cliente_id, numero:dadosSRS.sessao},
{$set: {'dadosSRS':dadosSessao.dadosSRS}},
function(result){
if (err) throw err;
console.log(result);
console.log('encontrou registo do cliente na collection registoSRS: ' + result);
});
but the result is null, although I have the client and the session number. What am I doing wrong?
In your callback you have only one argument which is essentially the error object hence the result is null since there is no error thrown from the update option. You need a second argument which returns the actual result object. You are using the wrong update method which returns the result object if the command was executed successfully, not the actual document.
From the documentation, the result object has the following properties:
Name Type Description
result Object The raw result returned from MongoDB, field will vary depending on server version.
Properties
Name Type Description
ok Number Is 1 if the command executed correctly.
n Number The total count of documents scanned.
nModified Number The total count of documents modified.
connection Object The connection object used for the operation.
matchedCount Number The number of documents that matched the filter.
modifiedCount Number The number of documents that were modified.
upsertedCount Number The number of documents upserted.
upsertedId Object The upserted id.
You instead need to use findOneAndUpdate which will return the updated document if found
const { ObjectId } = require('mongodb'); // or ObjectID
// or var ObjectId = require('mongodb').ObjectId if node version < 6
const safeObjectId = s => ObjectId.isValid(s) ? new ObjectId(s) : null;
collection.findOneAndUpdate(
{ 'cliente': safeObjectId(result.cliente_id), 'numero': dadosSRS.sessao },
{ '$set': { 'dadosSRS': dadosSessao.dadosSRS } },
{ 'returnOriginal': true },
function(err, result) { // <-- add result as a second argument in the callback
if (err) throw err;
console.log(result);
console.log('encontrou registo do cliente na collection registoSRS: ' + result);
});

_id of an Object in a Record changes on updating the data of the same object

I have an array of objects. Each object saves the Activity Types. I need to update one of the objects of the array. I used the _id for updating or deleting the object. So, when I pass id to update the data, I actually find the index of that object in the array and replace the data on that index with the new data.
Here the issue is that my _id also changes because I am not using $set or not directly updating using query. I am changing the data using map function and saving it to a mongoDB cursor which later at some place gets updated.
Below is the code and the output of the code.
organization.activityTypes = organization.activityTypes || [];
let findInd = organization.activityTypes.findIndex(x => x._id.toString() == (activityType.id?activityType.id.toString() : ''));
if(activityType.isDelete == true ) {
if(findInd > -1) organization.activityTypes.splice(findInd,1);
}
else if(findInd > -1) {
organization.activityTypes[findInd] ={
_id : activityType._id,
teams : activityType.teams == [] ? allTeams : activityType.teams ,
name: toTitleCase(activityType.name),
isDelete: activityType.isDelete,
custom : activityType.custom
}
}
else {
organization.activityTypes.push({
teams: activityType.teams == [] ? allTeams : activityType.teams,
name: toTitleCase(activityType.name),
isDelete: activityType.isDelete,
custom: activityType.custom
})
}
})
The output of the above code is given below.
This is the image of the output.
So, I changed the name of the activity Type. Initally its id is 5a15438482900b2aa6dc7ab1 then it converts to 5a15498cb024a02b4628e33f.
How can I prevent this change of _id in the database on every update?
I found that if I change the entire object at a particular index position, the _id of that indexed object will also get changed but if I only change fields of that objects,the object data will get updated but not the _id. My updated code is written below.
args.activityTypes.map((activityType)=> {
let findInd = organization.activityTypes.findIndex(x =>(x._id.toString() == (activityType.id?activityType.id.toString() : '')));
if(activityType.isDelete == true ) {
if(findInd > -1) organization.activityTypes.splice(findInd,1);
}
else if(findInd > -1) {
organization.activityTypes[findInd].teams = activityType.teams == [] ? allTeams: activityType.teams;
organization.activityTypes[findInd].name = toTitleCase(activityType.name);
organization.activityTypes[findInd].isDelete = Object.prototype.hasOwnProperty.call(activityType,'isDelete') ? activityType.isDelete :organization.activityTypes[findInd].isDelete;
organization.activityTypes[findInd].custom = Object.prototype.hasOwnProperty.call(activityType,'custom') ? activityType.custom :organization.activityTypes[findInd].custom;
}
else {
organization.activityTypes.push({
teams: activityType.teams == [] ? allTeams : activityType.teams,
name: toTitleCase(activityType.name),
isDelete: activityType.isDelete,
custom: activityType.custom
})
}
})

array manipulation in node js and lodash

I have two arrays
typeArr = [1010111,23342344]
infoArr={'name':'jon,'age':25}
I am expecting following
[{'name:'jone','age':25,'type':1010111,'default':'ok'},{'name:'jone','age':25,'type':23342344,'default':'nok'}]
Code :
updaterecord(infoArr,type)
{
infoArr.type=type;
response = calculate(age);
if(response)
infoArr.default = 'ok';
else
infoArr.default = 'nok';
return infoArr;
}
createRecord(infoArr,typeArr)
{
var data = _.map(typeArr, type => {
return updaterecord(infoArr,type);
});
return (data);
}
var myData = createRecord(infoArr,typeArr);
I am getting
[{'name:'jone,'age':25.'type':23342344,'default':nok},{'name:'jone,'age':25.'type':23342344,'default':nok}]
with some reason the last record updates the previous one. I have tried generating array using index var but not sure what's wrong it keep overriding the previous item.
how can I resolve this
You are passing the entire infoArr array to your updaterecord() function, but updaterecord() looks like it's expecting a single object. As a result it is adding those properties to the array rather than individual members of the array.
It's not really clear what is supposed to happen because typeArr has two elements and infoArr has one. Do you want to add another to infoArr or should infoArr have the same number of elements as typeArr.
Assuming it should have the same number you would need to use the index the _map gives you to send each item from infoArr:
function createRecord(infoArr,typeArr) {
var data = _.map(typeArr, (type, i) => {
// use infoArr[i] to send one element
return updaterecord(infoArr[i],type);
});
return (data);
}
Edit:
I'm not sure how you are calculating default since it's different in your expected output, but based on one number. To get an array of objects based on infoArray you need to copy the object and add the additional properties the you want. Object.assign() is good for this:
let typeArr = [1010111,23342344]
let infoArr={'name':'jon','age':25}
function updaterecord(infoArr,type){
var obj = Object.assign({}, infoArr)
return Object.assign(obj, {
type: type,
default: infoArr.age > 25 ? 'ok' : 'nok' //or however your figuring this out
})
}
function createRecord(infoArr,typeArr) {
return _.map(typeArr, type => updaterecord(infoArr,type));
}
Result:
[ { name: 'jon', age: 25, type: 1010111, default: 'nok' },
{ name: 'jon', age: 25, type: 23342344, default: 'nok' } ]

Resources