database.find{} problems with nedb in node.js-express - nedb

I am new with nedb in node.js
I have this database line
{"r":{"Processing_Equipment":"\"Diffusion Furnaces & Accessories\"","ID":"\"9102867\"","Model":"\"VTP 1500\"","Vintage":"\"1995\""},"searchValue":"search","_id":"oQXt8iTDbAhlOsxm"}
If I query
database.find{} either database.find{searchValue: "search"} ... etc everything goes fine.
But querying
database.find{{"r":{ID:"9102867"}}, (err, data) => {
if (err) {
response.end();
return;
}
console.log("found from database", data);
});
the data[] array is empty.
How can I query what within the r:{} field?
Thanks

Related

Postman how to export api response from collection runner with iteration to a file using node script

I am completely new to writing node scripts in Postman.
My requirement:
I have an api to get user details. I want to iterate for n number of users. I created a Runner collection and it executes. But i want to write each request response to a file.
Can anyone help me how to do this?
I watched some youtube video https://www.youtube.com/watch?v=cCRmry10874 for this. But my case is i have runner collection with data file.
When i exported the collection, i dont get the different values from data file.
const newman = require('newman');
newman.run({
collection: require('./collection.json'),
reporters: 'cli'
}, (err) => {
if(err) { throw err; }
console.log('collection run complete');
});
const fs = require('fs');
fs.writeFile('response.txt', 'Some text', (error) => {
if(error) {
console.error(error);
}
})
Thanks
Can you try it?
newman.run(
{
collection: require("./collection.json"),
reporters: "cli",
iterationData: "./data.json",
},
(err, summary) => {
if (err) {
throw err;
}
const results = summary.run.executions;
results.forEach((result) => {
fs.appendFileSync("response.txt", result.response.text());
});
}
);
If you are not limited to using a textfile, I would suggest using htmlextra.
It provides an HTML webpage with your runs and response body.

error Policy in Apollo Client React does'nt work

I have aproblem when test Apollo.When I try query with apollo and graphql, i want response return error and partical data, so I set property errorPolicy:'all'. But its not work. I don't no why? Help please!
Here my code:
query { animal {
name
age }, school {
name
numberfd } } `
const { loading,data,error} = useQuery(GET_DASHBOARD_DATA, {
errorPolicy:'all',
onCompleted: (res) => {console.log("complete",res)},
onError : (res,data) => {console.log("ERRRR",res,data)},
})
and i want to receive:
{
error:[...], data:[animal:[...]] }
but its only response error.Here is Apollo's doc: https://www.apollographql.com/docs/react/data/error-handling/
onError type is onError?: (error: ApolloError) => void;. You don't have data inside onError callback.
After useQuery you can add:
console.log('data', data)
console.log('error', error)
I faced the same issue with errorPolicy: 'all', I only received the partial result inside onCompleted callback of useQuery, but no errors.
I created an ErrorLink like this:
private createErrorLink = () => {
return new ApolloLink((operation, forward) => {
return forward(operation).map((response) => {
// filter out errors you don't want to display
const errors = filterSomeErrors(response.errors);
if (errors && response?.data) {
response.data.errors = errors;
}
return response;
});
});
};
Now inside my onCompleted callback I get my data as well as errors. You will have to tweak your types a bit, because seems there is no errors field on response.data by default.
Mind that if you use onError from Apollo and return something from the link, it will retry your request containing errors!

How to POST correctly a form that have data and files with VueJS, Axios and Laravel?

I am posting here as a beginner of VueJS and Laravel. I am stuck with a problem that I can't fix by myself after hours of search.
I would like to know how correctly send and get back the inputs of a form (complex data and files).
Here is the submit method of the form:
onSubmit: function () {
var formData = new FormData();
formData.append("data", this.model.data);
formData.append("partData", this.model.partData);
if (this.model.symbolFile != null) {
formData.append("symbolFile", this.model.symbolFile);
}
if (this.model.footprintFile != null) {
formData.append("footprintFile", this.model.footprintFile);
}
axios
.post("/api/updatecomponent", formData, {
headers: {
"Content-Type": "multipart/form-data",
},
})
.then((res) => {
// do something with res
// console.log(res);
})
.catch((err) => {
/* catch error*/
console.log(err);
});
},
The variable Data and PartData contains multiple string fields which will be stored in different tables in my database. Example :
Data
{
string Value,
string Tolerance,
string Power
}
Here is the method of the Controller in the server side:
public function updateComponent(Request $req)
{
$data = $req->input('data');
$partData = $req->input('partData');
$symbolFile = $req->file('symbolFile'); // is null if the user did not modify the symbol
$footprintFile = $req->file('symbolFile'); // is null if the user did not modify the footprint
// etc...
}
I am able to get the files, everything work for that and I can store and read them :)
But, the problem is that I am unable to get back properly my Data or PartDat.
When I do :
dd($partData);
I got as result in the console:
"[object Object]"
I am almost sure that I don't use correctly the FormData but after hours of search, I can't find the good way I should gave the Data and PartData to the FormData.
My code was working well for Data and PartData until I add FormData to support the file upload :(
Thank you for your help :)
Here my working code:
Client side:
var formData = new FormData(); // create FormData
formData.append("subcat", this.subcategory);// append simple type data
formData.append("data", JSON.stringify(this.model.data));// append complex type data
axios // send FormData
.post(url, formData, {
headers: {
"Content-Type": "multipart/form-data",
},
})
.then((res) => {
// do something with res
// console.log(res);
})
.catch((err) => {
/* catch error*/
console.log(err);
});
Server side:
public function createComponent(Request $req)
{
$subcategory = $req->input('subcat'); // get the input parameter named 'subcat' (selected subcategory)
$data = json_decode($req->input('data'), true); // get the input, decode the jason format, force to return the result as an array
}
I hope it will help other peoples :)
Simple solution
let data = new FormData();
data.append('image',file_name.value);
_.each(form_data, (value, key) => {
data.append(key, value)
})
console.log('form data',data);
Now you can get data in laravel controller like:
$request->title
$request->description
$request->file

Is there anyway to query mongodb in cypress test?

I am looking to interact with mongodb from cypress test.I couldn't find any useful documentation.Please help me how to acheive this?
Look at their documentation about tasks :https://docs.cypress.io/api/commands/task.html#Command
I needed to do something with mongodb and i managed to connect doing something like this (inside "plugins" directory):
const MongoClient = require('mongodb').MongoClient;
module.exports = (on, config) => {
on('task', {
updateTask (id) {
return new Promise((resolve) => {
MongoClient.connect('mongodb://localhost:27017', (err, client) => {
if (err) {
console.log(`MONGO CONNECTION ERROR: ${err}`)
throw err;
} else {
const db = client.db('myDB');
db.collection('someCollection').count({}, function(error, numOfDocs){
resolve({success: numOfDocs})
client.close();
})
}
});
}); // end of return Promise
}
}) // end of task
}
and you call it inside "spec" like this:
cy.task('updateTask', someParam).then((textOrNull) => {
console.log(textOrNull)
})
There is now a mongodb plugin for cypress: https://www.npmjs.com/package/cypress-mongodb
After you configure it, you'll be able to call cy commands to perform actions in your local or remote db:
cy.createCollection(...);
cy.dropCollection(...);
cy.insertMany(...);
cy.aggregate(...);
Execute a shell command from your cypress test:
https://docs.cypress.io/api/commands/exec.html#Syntax
Example:
cy.exec(mongo mydatabase --eval 'db.collection.find({})')

How to sort find query by date?

I am inserting data using this query:
database.insert({ postedAt: new Date() }, (error: any, doc: any) => {
if (error) {
console.log ('Error inserting record in the database: ', error);
} else {
console.log('Document: ', doc);
}
});
This is stored in the database:
{"postedAt":{"$$date":1557753437242},"_id":"PJL2N6hfkvKnTTRK"}
Then I want to find data sorted by latest input to show up first:
this.database.find({}).exec(function(err: any, docs: any) {
docs.forEach(function(d: any) {
console.log('Found user:', d);
});
});
Question 1: But how can I ensure I get only the latest record?
Question 2: How can I get all records within 24 hours?
Thank you!
nedb supports sort by date out of the box, just sort it and limit 1
db.find({}).sort({postedAt: -1}).limit(1).exec((err, docs)=>{
console.log(docs[0]);
})

Resources