PouchDB emit object from an array of objects - javascript

I would like to search trough an array of objects (that are encapsulated in one big object), and emit only the one of the internal objects. So let's suppose I have a JSON inserted into PouchDB that is looks like this:
{
"_id": "5eaa6d20-2019-44e9-8aba-88cfaf8e02542",
"data": [
{
"id": 1452,
"language": "java"
},
{
"id": 18787453,
"language": "javascript"
},
{
"id": 145389721,
"language": "perl"
}
]
}
How to get PouchDB to return the following result when searching for a language with an id = 145389721:
{
"id": 145389721,
"language": "perl"
}
Thanks!

In the scenario above the easiest way, using typescript, is to write a temp query:
db.query((doc, emit) => {
for (let element of doc.data) {
if (element.id === 145389721) {
emit(element);
}
}
}).then((result) => {
for (let row of result.rows) {
console.log(row.key);
}
})
Using permanent queries it would have looked like this:
let index = {
_id: '_design/my_index',
views: {
"by_id": {
"map": "function(doc) {for (let element of doc.data) {emit(element.id, element); }}"
}
}
};
// save it
this.db.put(index).catch(error => {
console.log('Error while inserting index', error);
});
//query it
this.db.query('my_index/by_id', { startkey: 145389721, endkey: 145389721}).then(result => {
for (let row of result.rows) {
console.log(row.value);
}
}).catch(error => {
console.log('Error while querying the database with an index', error);
});

Related

Convert the simple fetch API code to ".then" notation code

How can I covert following code into .then notation. I wanted to strictly use ".then" notation. That is what I observed with my system.
I raised one question with similar kind of request however, I got the code using async/await. Rather than asking the new requirement over the same thread I initiated this new thread.
Apology for inconvenience. I should have posted this it in first thread itself. Kindly help.
var obj = [{"Id":"10101","descr":"server1.com"},{"Id":"10102","descr":"server2.com"},{"Id":"10103","descr":"server3.com"},{"Id":"10104","descr":"server4.com"},{"Id":"10105","descr":"server5.com"},{"Id":"10106","descr":"server6.com"},{"Id":"10107","descr":"server7.com"}];
var temp = [];
for (var i = 0; i < obj.length; i++){
var id = obj[i].Id;
let response = await fetch('https://abced.com/api/'+id+'/value', {method : "GET", headers: {"Authorization": "xyz"}});
var data = await response.json();
var stats = data.status;
if (stat != "OK")
{
temp.push({Id:obj[i].Id, descr:obj[i].descr, value:"ERROR"})
}
}
console.log(temp);
My expected output is, (values of Id and descr will depends on "if statement" in the code)
[{"Id": "10101","descr": "server1.com","status": "ERROR"},
{"Id": "10103","descr": "server3.com","status": "ERROR"},
{"Id": "10104","descr": "server4.com","status": "ERROR"}]
I tried following but in my system compiler says, "Function declared within loops referencing an outer scope variable mat lead to confusing semantics (Id, descr)"
function fetchMock(url) {
let id = url.split('/')[4];
if ([10101, 10103, 10104].includes(+id)) {
return Promise.resolve({
json() {
return Promise.resolve({
status: 'BAD'
});
}
});
} else {
return Promise.resolve({
json() {
return Promise.resolve({
status: 'OK'
});
}
});
}
}
var obj = [{
"Id": "10101",
"descr": "server1.com"
},
{
"Id": "10102",
"descr": "server2.com"
},
{
"Id": "10103",
"descr": "server3.com"
},
{
"Id": "10104",
"descr": "server4.com"
},
{
"Id": "10105",
"descr": "server5.com"
},
{
"Id": "10106",
"descr": "server6.com"
},
{
"Id": "10107",
"descr": "server7.com"
}
];
function getResults() {
const results = [];
for (let {
Id,
descr
} of obj) {
fetchMock('https://abced.com/api/' + Id + '/value', {
method: "GET",
headers: {
"Authorization": "xyz"
}
}).then(res => res.json()).then(function(data) {
if (data.status !== 'OK') {
results.push({
Id,
descr,
value: 'ERROR'
});
}
});
}
return results;
}
function test() {
const results = getResults();
return results;
}
test();

Using strapi V4 graphql and nextjs - filters not work

I´m using strapi V4 with the graphql extension. When i´m use filters with variables in the graphql Playground there are no problems.
query getOrdersFilterList($searchstring: String!) {
orders(filters: { customer: { contains: $searchstring } }) {
data {
attributes {
number
customer
name
article
}
}
}
}
Query Variables:
{
"searchstring": "zi"
}
When i use filters with Postman no problems.
query getOrdersFilterList($searchstring: String) {
orders(filters: {customer: { containsi: $searchstring}}) {
data {
attributes {
number
customer
name
article
}
}
}
}
Graphql Variables :
{
"searchstring": "zi"
}
The result is like expected:
{
"data": {
"orders": {
"data": [
{
"attributes": {
"number": "30072",
"customer": "Stauder Zimmerei",
"name": "Hagmann Habsburgerstr.",
"article": "Stahlteile "
}
},
{
"attributes": {
"number": "22-02-015 A",
"customer": "Ziebarth Wolfgang",
"name": "Austr. 1 a",
"article": "Aussengeländer "
}
},
{
"attributes": {
"number": "30013",
"customer": "Ziser",
"name": "Bürklinstraße 7, Lahr",
"article": "Geländer mit Mlichglas "
}
}
]
}
}
}
Now my nextjs app code:
export const getOrdersFilterList = async (page, pageSize, searchstring) => {
const data = await client.query({
query: gql`
query getOrdersFilterList($searchstring: String) {
orders(filters: {customer: { contains: $searchstring}}){
data {
attributes {
number
customer
name
article
}
}
}
}`,
variables: {searchstring}
})
Variables same as above ( searchstring come from the call of the function )
{
"searchstring": "zi"
}
this is what i get on the console (Firefox):
" Object { data: {…}, loading: false, networkStatus: 7 } "
I spend days to search. I can´t find a clue
Anyone can help ?
solved !
The Problem was the Variable
{
"searchstring": "zi"
}
In every Tutorial or example i find it like above.
But the only thing your Variable must contain is
zi
let´s explain in the code :
export const getOrdersFilterList = async () => {
// this is the variable
const searchstring = "zi"
// thats all
const data = await client.query({
query: gql`
query getOrdersFilterList($searchstring: String) {
orders(filters: {customer: { containsi: $searchstring}}){
data {
attributes {
number
customer
name
article
}
}
}
}`,
variables: {searchstring}
})

Update mongo collection with values from a javascript map

I have a collection that looks like this
[
{
"project":"example1",
"stores":[
{
"id":"10"
"name":"aa",
"members":2
}
]
},
{
"project":"example2",
"stores":[
{
"id":"14"
"name":"bb",
"members":13
},
{
"id":"15"
"name":"cc",
"members":9
}
]
}
]
I would like to update the field members of the stores array taking getting the new values from a Map like for example this one
0:{"10" => 201}
1:{"15" => 179}
The expected result is:
[
{
"_id":"61",
"stores":[
{
"id":"10"
"name":"aa",
"members":201
}
]
},
{
"_id":"62",
"stores":[
{
"id":"14"
"name":"bb",
"members":13
},
{
"id":"15"
"name":"cc",
"members":179
}
]
}
]
What are the options to achieve this using javascript/typescript?
In the end, I resolved by updating the original database entity object with the values in the map, then I have generated a bulk query.
for (let p of projects) {
for(let s of p.stores) {
if(storeUserCount.has(s.id)){
s.members = storeUserCount.get(s.id);
}
};
bulkQueryList.push({
updateOne: {
"filter": { "_id": p._id },
"update": { "$set": {"stores": p.stores} }
}});
};
await myMongooseProjectEntity.bulkWrite(bulkQueryList);
You can use update() function of Mongoes model to update your expected document.
Try following one:
const keyValArray= [{"10": 201},{"15":"179"}];
db.collectionName.update({_id: givenId},
{ $push: { "stores": {$each: keyValArray} }},
function(err, result) {
if(err) {
// return error
}
//return success
}
});

Add copy to to eslaticsearch on index template

I use elasticsearch 6.2, and I want to optimize the elasticsearch search functionality to copy all field value to one value and generate than searching by query string on one field instead of multiple field. How to do that? How to copy all fields, now matter which to one filed.
initialize index template
export const init = async types => {
try {
let client = createClient()
const templateSettings = {
index_patterns : ['*'],
settings: indexTemplateSettings,
mappings : types.reduce((p, type) => ({
...p,
[type] : {
numeric_detection: true,
_source : {enabled : true},
'properties': {
'searchIndex': {
'type': 'text',
},
'*': {
'type': 'text',
'copy_to': 'searchIndex',
},
},
},
}), {}),
}
await client.indices.putTemplate({
name: 'default',
body: templateSettings,
},(error, response) => {
logger.silly('Pushing of index template completed', response)
})
} catch (e) {
logger.error(e)
}
}
put index
export const push = (message, type) => new Promise(async resolve => {
try {
let client = createClient()
let indexCreationTime = new Date('2016-02-08').toISOString().substring(0, 10)
// '2016-02-08'
console.log(message, 'message')
console.log(type, 'type')
await client.index({
index: type.toLowerCase(),
type,
body: {
...message,
_timestampIndex: indexCreationTime,
},
},
(error, response) => {
logger.silly('Pushing of data completed', response)
resolve(response)
})
} catch (e) {
logger.error(e)
}
})
The best way is to create an index template which leverages a dynamic template that will catch all fields and add the copy_to parameter to their definition.
PUT _template/my-template
{
"index_patterns": ["*"],
"settings": {},
"mappings": {
"_doc": {
"dynamic_templates": [
{
"all": {
"match": "*",
"mapping": {
"type": "text",
"copy_to": "searchIndex"
}
}
}
],
"properties": {
"searchIndex": {
"type": "text"
}
}
}
}
}

How to extract some data from json in react JS (axios)?

I'm a ReactJS and axios newbie.
I want to iterate and extract json data if the key is number (like 0, 1, 2....)
and don't know how can I write this piece of code.
(because the server provide the json dynamically, and we don't know how many elements it will have)
Now I can extract the data with key = 0 (assume there exists this element)
class ContentBody extends Component {
constructor(props) {
super(props);
this.state = {
jdata: []
}
}
componentDidMount() {
var self = this;
// read data periodically
setInterval(function() {
axios.get(URL)
.then(function(response) {
self.setState({
jdata: response.data[0].Name
});
})
.catch(function(e) {
console.log("ERROR ", e);
})
}, 1000);
}
}
// below is json data from the server
{
"0": {
"Assigned": false,
"Name": "BebopDrone-Test001.",
"droneID": 0
},
"1": {
"Assigned": false,
"Name": "BebopDrone-B046836",
"droneID": 1
},
"2": {
"Assigned": false,
"Name": "BebopDrone-Test002.",
"droneID": 2
},
"function": "getAllDroneStatus()"
}
// my pseudo code might be
for(int i = 0; i < jsonObject.size(); i++){
if(key is number){
extract corresponding value
}
}
The response that you get from the server is an object, what you should do is loop over the Object and then update data in state where I assume you only need name
componentDidMount() {
var self = this;
// read data periodically
setInterval(function() {
axios.get(URL)
.then(function(response) {
var names=[];
Object.keys(response.data).forEach(function(data) {
names.push(data.Name);
})
self.setState({
jdata: names
});
})
.catch(function(e) {
console.log("ERROR ", e);
})
}, 1000);
}
Your response is an Object not an Array.
You can't access an object using array indexing.
Assuming response.data is the body of your json, you should access your object properties like this: response.data['0'], response.data['1'], response.data['2']
You can iterate over an object using for..in.
Your data model (aside from the reference to 'getAllDroneStatus()') suggests that an array might be more useful.
{
"jdata" : [
{
"Assigned": false,
"Name": "BebopDrone-Test001.",
"droneID": 0
}
// ...
]
}
Then you can iterate, reduce, filter and so on.

Categories

Resources