I've got the following json response:
{
"vin": "BAUV114MZ18091106",
"users": [
{
"role": "PRIMARY_USER",
"status": "ACTIVE",
"securityLevel": "HG_2_B",
"firstName": "Etienne",
"lastName": "Rumm",
"nickName": "BastieW",
"isInVehicle": false
},
{
"role": "SECONDARY_USER",
"status": "ACTIVE",
"securityLevel": "HG_2_B",
"firstName": "Test",
"lastName": "DEde",
"isInVehicle": false
}
]
}
I want to test the "isInVehicle" key and pass the test, if it's true and fail the test, if it's false.
I was trying to do so with following test code, but it didn't work, tests are always passed, no matter what response I got.
pm.test("User is in Vehicle", () => {
_.each(pm.response.json(), (arrItem) => {
if (arrItem.isInVehicle === 'true') {
throw new Error(`Array contains ${arrItem.isInVehicle}`)
}
})
});
Are there any ideas on how to solve my problem?
I think you are iterating through an object(root object of your response) instead of the user array. The revised version would be:
var users = pm.response.users;
_.each(users, (arrItem) => {
if (arrItem.isInVehicle) {
//Do something if isInVehicle is true
}
})
});
You can do these using array properties,
some - returns true if at least one match the condition
every - returns true if all items match the condition
const response = {
"vin": "BAUV114MZ18091106",
"users": [{
"role": "PRIMARY_USER",
"status": "ACTIVE",
"securityLevel": "HG_2_B",
"firstName": "Etienne",
"lastName": "Rumm",
"nickName": "BastieW",
"isInVehicle": false
},
{
"role": "SECONDARY_USER",
"status": "ACTIVE",
"securityLevel": "HG_2_B",
"firstName": "Test",
"lastName": "DEde",
"isInVehicle": false
}
]
};
pm.test("User is in Vehicle", () => {
// I'm assuming you are looking for atleast one match
const atleastOneMatch = response.users.some(user => user.isInVehicle);
// if you are looking for all should match, uncomment the following code
// const allShouldMatch = response.users.every(user => user.isInVehicle);
if(atleastOneMatch) {
// do your stuffs here
}
})
Related
I am using node.js and I am getting data from firebase real-time database. The problem is I am getting data something like this :
for data getting code! JS
import firebaseApp from '../config.js';
import { getDatabase, ref, onValue } from "firebase/database";
const userRef = ref(database, "Users");
onValue(userRef, (snapshot) => {
if (snapshot.exists) {
const data = snapshot.val();
console.log(data); // data printed to console
}
}, {
onlyOnce: true
});
Console Output
{
"random-user-id-1": {
"name": "Jhon Doe",
"profile": "profilelink",
"email": "example#email.com"
},
"random-user-id-2": {
"name": "Cr7",
"profile": "profilelink",
"email": "example#email.com"
},
// and more...
}
I want to display this data as an array of objects. Example of expected output
[
{
"name": "Jhon Doe",
"profile": "profilelink",
"email": "example#email.com"
},
{
"name": "Cr7",
"profile": "profilelink",
"email": "example#email.com"
}
// and more........ ^_~
]
Any help will be always appreciated! and feel free to ask any doubts related to my question or problem!
thank you :)
seems like you need only the values from your dict, you can transform your data this way:
const lst = {
"random-user-id-1": {
"name": "Jhon Doe",
"profile": "profilelink",
"email": "example#email.com"
},
"random-user-id-2": {
"name": "Cr7",
"profile": "profilelink",
"email": "example#email.com"
},
}
const expectedFormatRes = Object.values(lst);
console.log(expectedFormatRes);
An alternative to Gil's answer would be to use Firebase's built-in. forEach operation:
if (snapshot.exists) {
let values = [];
snapshot.forEach((child) => {
value.push(child.val());
})
console.log(values);
}
While longer, this has the advantage that it maintains the order in which the database returned the data, which becomes relevant when you specify an orderBy... clause on your query..
I have some JSON as shown below...
var JSONobj = {
"headline":{
"localized":{
"en_US":"Doctor"
},
"preferredLocale":{
"country":"US",
"language":"en"
}
},
"identities":[
{
"access_token":"AQVUTBfbOs5JLsdfsdfH_W1aZ2N0PrbL0LhD5Y5-g",
"provider":"linkedin",
"user_id":"v57678565vf",
"connection":"linkedin",
"isSocial":true
},
{
"access_token":"AQVUTBsdfsdfsdfsdfwePrbL0LhD5Y5-g",
"provider":"facebook",
"user_id":"hshs8722",
"connection":"facebook",
"isSocial":true
}
],
"name":"John Bob"
};
Using JavaScript I need to go through each item in the "identities" array, find the item with a "connection" value of "facebook", and return the associated "access_token" value.
Note: This example has two items in the "identities" array, but in production there will a dynamic number of items. Sometimes more, sometimes less.
I have been trying to do it using map() as shown below, but I can't figure it out.
var access_token = JSONobj.identities.map(i=>i.connection);
console.log(access_token);
You can use Array.find to find the first object in identities that has a connection of "facebook", then extract the access_token from that object:
var JSONobj = {
"headline": {
"localized": {
"en_US": "Doctor"
},
"preferredLocale": {
"country": "US",
"language": "en"
}
},
"identities": [{
"access_token": "AQVUTBfbOs5JLsdfsdfH_W1aZ2N0PrbL0LhD5Y5-g",
"provider": "linkedin",
"user_id": "v57678565vf",
"connection": "linkedin",
"isSocial": true
},
{
"access_token": "AQVUTBsdfsdfsdfsdfwePrbL0LhD5Y5-g",
"provider": "facebook",
"user_id": "hshs8722",
"connection": "facebook",
"isSocial": true
}
],
"name": "John Bob"
};
var access_token = JSONobj.identities.find(o => o.connection == 'facebook').access_token;
console.log(access_token);
Note (as pointed out by #secan) that if it's possible that there might not be an identity with a connection of "facebook", it is safer to use:
(JSONobj.identities.find(i=>i.connection === 'facebook')||{}).access_token;
as this will return undefined rather than raising an error.
Another alternative in that situation (as pointed out by #pilchard) is to use optional chaining (although this requires a fairly recent browser for support):
JSONobj.identities.find(i=>i.connection === 'Facebook')?.access_token;
create a generala function wich accept identities array and required connection name,
you can use Array.find to go through connection array items
function getAccessToken(identitiesArr, connection) {
let identity = identitiesArr.find(e => e.connection == connection);
if (identity)
return identity.access_token;
return '';
}
var JSONobj = {
"headline": {
"localized": {
"en_US": "Doctor"
},
"preferredLocale": {
"country": "US",
"language": "en"
}
},
"identities": [{
"access_token": "AQVUTBfbOs5JLsdfsdfH_W1aZ2N0PrbL0LhD5Y5-g",
"provider": "linkedin",
"user_id": "v57678565vf",
"connection": "linkedin",
"isSocial": true
},
{
"access_token": "AQVUTBsdfsdfsdfsdfwePrbL0LhD5Y5-g",
"provider": "facebook",
"user_id": "hshs8722",
"connection": "facebook",
"isSocial": true
}
],
"name": "John Bob"
};
let token = getAccessToken(JSONobj.identities, "facebook");
console.log(token);
I am doing a Node.js REST API tutorial. I use Express, Knex.js (0.19.0) and PostgreSQL.
I have two database tables, users:
// user_migration.js
exports.up = function(knex) {
return knex.schema.createTable('users', function(table) {
table
.increments('id')
.primary()
.unsigned();
table.string('firstName');
table
.string('lastName')
.index()
.notNullable();
table
.string('email')
.unique()
.index()
.notNullable();
table.string('password').notNullable();
table.string('role').defaultTo('STAFF');
table.boolean('isActive').defaultTo(false);
table.timestamp('createdAt').defaultTo(knex.fn.now());
table.timestamp('updatedAt').defaultTo(knex.fn.now());
});
};
and posts:
// post_migration.js
exports.up = function(knex) {
return knex.schema.createTable('posts', function(table) {
table
.increments('id')
.primary()
.unsigned();
table.string('title').notNullable();
table.text('body');
table.boolean('published').defaultTo(false);
table
.integer('author')
.unsigned()
.index()
.references('id')
.inTable('users')
.onDelete('SET NULL');
table.timestamp('createdAt').defaultTo(knex.fn.now());
table.timestamp('updatedAt').defaultTo(knex.fn.now());
});
};
I want to make a GET request at http://localhost:8081/users/1/posts to show user.id 1's posts.
// user_get.js
async getPosts(req, res, next) {
try {
// Check if user exists
const user = await this.knex('users')
.where('id', req.params.id)
.first();
// If not, return NOT FOUND status code
if (!user) return next(createError(404, 'User not found'));
/**
* Right here, I am not sure if I am doing it right.
*/
// Get from database and filter
const result = await this.knex('users')
.join('posts', 'posts.author', '=', 'users.id')
.select()
.then(posts => posts.filter(post => post.author === user.id));
// Return OK status code and related posts
res.status(200).send(result);
} catch (error) {
// Return BAD REQUEST status code
return next(createError(400, error);
}
}
What I expected is an array of posts belong to user 1:
[
{
"id": 1,
"title": "Number One Post",
"body": "This is the one body",
"published": true,
"author": 1,
"createdAt": "2019-07-23T06:14:04.281Z",
"updatedAt": "2019-07-23T06:14:04.281Z"
},
{
"id": 2,
"title": "Number Two Post",
"body": "This is two body",
"published": false,
"author": 1,
"createdAt": "2019-07-23T06:14:04.281Z",
"updatedAt": "2019-07-23T06:14:04.281Z"
}
]
But I got like this:
[
{
"id": 1,
"firstName": "Some",
"lastName": "One",
"email": "some#one.com",
"password": "password789",
"role": "STAFF",
"isActive": false,
"createdAt": "2019-07-23T06:14:04.281Z",
"updatedAt": "2019-07-23T06:14:04.281Z",
"title": "Number One Post",
"body": "This is the one body",
"published": true,
"author": 1
},
{
"id": 2,
"firstName": "Some",
"lastName": "One",
"email": "some#one.com",
"password": "password789",
"role": "STAFF",
"isActive": false,
"createdAt": "2019-07-23T09:21:34.285Z",
"updatedAt": "2019-07-23T09:21:34.285Z",
"title": "Number Two Post",
"body": "This is two body",
"published": false,
"author": 1
}
]
How should I query user 1's posts without mashing up with user info?
Please help.
P.S. Also updatedAt in Knex.js does not work correctly. It does not update the timestamp when I update. How do I fix this?
Just drop your join on users in the second query
const result = await this.knex('posts')
.where('posts.author', user.id)
.select()
// Return OK status code and related posts
res.status(200).send(result);
I am trying to add a property on an Observable after subscribing and assigning the response in my Angular 4 app.
getCourses() {
return this.coursesService.getCourses().subscribe(
res => {
this.courses = res;
for (const course of this.courses) {
course.isChecked = false;
}
}
);
}
The code works and creates the property on the Observable but I get the error below as well.
ERROR TypeError: Cannot create property 'isChecked' on boolean 'false' at SafeSubscriber._next at SafeSubscriber.webpackJsonp.../../../../rxjs/Subscriber.js.SafeSubscriber.__tryOrUnsub
How can I correct the code so that I don't get errors?
Solved!!!
So I didn't realize that at the end of the array of objects that the api was returning was false.
[{ "PersonID": "129", "FirstName": "Ash", "MiddleName": "E.", "LastName": "Green", "MemberID": "129346", "MemberNumber": "105", "MemberStatus": 2, "AffiliatedAgencyID": "160" }, { "PersonID": "221334", "FirstName": "Abs", "MiddleName": null, "LastName": "Plast", "MemberID": "1953", "MemberNumber": "2047", "MemberStatus": 1, "AffiliatedAgencyID": "13" }, false]
Once I created an if statement to account for the false at the end, my problem was fixed. The other object I was getting doesn't have this anomaly. So it wasn't happening.
If res is an array, you should be able to go trough it without any problem. But make sure that res is an array.
getCourses() {
return this.coursesService.getCourses()
.subscribe(res => this.courses = res.map(course => course.isChecked = false));
}
So I didn't realize that at the end of the array of objects that the api was returning was false.
[{ "PersonID": "129", "FirstName": "Ash", "MiddleName": "E.", "LastName": "Green", "MemberID": "129346", "MemberNumber": "105", "MemberStatus": 2, "AffiliatedAgencyID": "160" }, { "PersonID": "221334", "FirstName": "Abs", "MiddleName": null, "LastName": "Plast", "MemberID": "1953", "MemberNumber": "2047", "MemberStatus": 1, "AffiliatedAgencyID": "13" }, false]
Once I created an if statement to account for the false at the end, my problem was fixed. The other object I was getting doesn't have this anomaly. So it wasn't happening.
I have these two models:
Student
{
"name": "student",
"plural": "students",
"base": "User",
"idInjection": false,
"options": {
"validateUpsert": true
},
"relations": {
"test": {
"type": "embedsMany",
"model": "test",
"property": "mytest",
"options": {
"validate": true,
"forceId": false
}
}
}
and
Test
{
"name": "test",
"base": "Model",
"idInjection": true,
"options": {
"validateUpsert": true
},
"properties": {
"text": {
"type": "string",
"required": true
}
}
}
When I try to create a new test I get this error
Error: Invalid reference: undefined
I create the test in this way:
Student.js
studentInstance.test.add({text : "something "})
What am I doing wrong?
Update
Delete in embedsMany
update id in test.
Student.js
Student.show = function(email, cb) {
Student.findById(email,function(err, student) {
...
var tmp = student.mytest;
for (var i = 0; i < tmp.length; i++) {
student.test.destroy(tmp[i].id);
}
})
...
}
I tried with
destroy not work correctly, not always remove the data
and
remove show this error
Error: Invalid reference: undefined
at EmbedsMany.remove
Update
Added a example of db
{
"_id": "value",
"property1": "value",
.
.
"mytest": [
{
"text": "something",
"creation": {
"$date": "2016-08-23T14:31:44.678Z"
},
"id": "d738253472876b17feb4b46b"
}
]
}
You don't have test model.
In test.json you defined its names as notification => "name": "notification",
UPDATE
For building (without persisting) an embedded instance please use studentInstance.test.build({text : "something "})
and for creating (with persisting) that please use studentInstance.test.create({text : "something "})
After 3 years, I've faced with same problem by using remove, destroyById.
And then I use unset method. It works.
Person.findById(body.metadata.person.id, (err, person) => {
person.creditCards.unset(
body.creditCard.id,
(err, res) => {
}
);
}
This works well.