How to sort find query by date? - nedb

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]);
})

Related

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

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

Error writing result to store for query. Cannot read property 'query' of undefined

I'm getting an error when writing a query to store after a mutation. The mutation works and i'm able to read the query post mutation. When i write the same query to the store cache i get the following Error:
index.js:2178 Error: Error writing result to store for query:
query ($applicationId: Int) {
vApplicationApprovalChainList(ApplicationId: $applicationId) {
id
approvalOrder
approverId
name
applicationId
__typename
}
}
Cannot read property 'vApplicationApprovalChainList' of undefined
at writeToStore.js:101
at Array.forEach (<anonymous>)
at writeSelectionSetToStore (writeToStore.js:97)
at writeResultToStore (writeToStore.js:75)
at InMemoryCache../node_modules/apollo-cache-inmemory/lib/inMemoryCache.js.InMemoryCache.write (inMemoryCache.js:99)
Here is my code.. the mutation and store.readQuery works but the store.writeQuery gives above error. Thank you in advance for any feedback.
APPROVERSLIST_QUERY = gql`
query ($applicationId:Int){
vApplicationApprovalChainList(ApplicationId:$applicationId){
id
approvalOrder
approverId
name
applicationId
}
}
`;
handleClick() {
const { row, mutate} = this.props;
mutate({
variables: {
id: row.id
},
update: (store, { data: { deleteApprover } }) => {
const newdata = store.readQuery({
query: APPROVERSLIST_QUERY,
variables: { applicationId: row.applicationId }
});
console.log(newdata);
newdata.vApplicationApprovalChainList = newdata.vApplicationApprovalChainList.filter(approver => approver.id !== deleteApprover.id);
store.writeQuery({
query: APPROVERSLIST_QUERY, newdata });
}
});
}
You're not passing in the new data to writeQuery. The object passed to writeQuery must have a property named data containing the new data. Additionally, since your query contains variables, you will need to include that information as well.
store.writeQuery({
query: APPROVERSLIST_QUERY,
data: newdata,
variables: {
applicationId: row.applicationId,
},
});
Please see the official docs for more examples and a more thorough explanation of the two methods.

Sort order table.getRows

In the following simple example 'foo.csv' is a simple 3 column table.
The first column is the line number. The second and third columns are strings.
I create the table using schema auto-detection.
(I've also tried creating a table with a specific schema with similar results.)
I then query it using table.getRows.
The rows returned are not in the order they were inserted.
It took me a while to figure out the order, since it's neither order of insertion nor numerically by the first column.
The sort order is
- Length of second column
- Alphabetically by second column
- Length of third column
- Alphabetically by third column
which is completely useless as far as I'm concerned.
How can I either A) preserve the insertion order or B) sort by the first column?
This seems like a relatively straightforward request but I can't find any documentation on it.
const gcloud = require('google-cloud');
const storage = gcloud.storage();
const bigquery = gcloud.bigquery({ projectId: projectId });
const async = require('async');
const bucket = storage.bucket(storage.bucket);
const file = bucket.file('foo.csv');
const dataset = bigquery.dataset('dataset1');
const table = dataset.table('table1');
async.waterfall([
(callback) => {
table.import(file, {
autodetect: true,
maxBadRecords: 500000,
writeDisposition: 'WRITE_TRUNCATE',
}, callback);
},
(job, apiResponse, callback) => {
async.retry({
times: 20000,
interval: 2000
}, (retryCallback, results) => {
job.getMetadata((err, metadata) => {
let status = metadata.status.state;
retryCallback((status == 'DONE') ? null : status);
});
}, callback);
},
(callback) => {
table.getRows({
autoPaginate: false,
maxResults: 100
}, callback);
},
(rows, nextQuery, info, callback) => {
rows.forEach((row) => {
console.log(JSON.stringify(row));
});
callback(null);
}
], (err) => {
console.log(err);
});
Instead of using table.getRows you can use table.query to pass an SQL query in which you could specify the sort using an Order By clause.
https://googlecloudplatform.github.io/google-cloud-node/#/docs/bigquery/0.3.0/bigquery/table?method=query

how to use query result (single row or multiple row) data from node-mysql

I have successfully get data by performing query with node-mysql. But i cant use the query result.
My query result is
{
user_id: 'joy',
user_name: 'joy',
email: 'joy#gmail.com',
socket_id: '/#glVfkRwTqKrlBETiAAAH',
status: 1 }
To use this from i wrote code like :
var value= [];
value = connection.query('SELECT * FROM socket_users WHERE email = ?',[receiver_email], function (error, results,fields) {
// Neat!
if (error) throw error;
console.log(results[0]);
if (results[0].status == 0) {
}else {
console.log("User is online......");
}
//console.log("select one user sql: "+is_Exists.sql);
});
But i got errors at results[0].status line. It says
TypeError: Cannot read property 'status' of undefined
After searching to solve my problem i found a solution. results is an array of an object. So , to use this;
just call
results [array number ]. row attribute name
results[i].status
results[i].user_name
// where i is an integer number

Parse.com Slow Queries Analytics - Query with empty where-clause

my backend is made with parse.com Now I experienced in the Parse.com Analytics-Section the Tab "Slow Queries". Nice feature to see how your queries are performing.
Now what I see there is that there are queries of mine with empty where clauses you can see it here:
Users where:{ facebookID: ... }
Friends where:{ user: ... }
Friends where:{ objectId: ... }
Users where:{}
Friends_Rel where:{ friend: ..., user: ... }
Friends_Rel where:{}
Now my question is why are there empty where clauses? Because I assume that this Query results in an error and it is not wanted by me I think.
I always build my queries either like this:
var query = new Parse.Query("Friends_Rel");
query.equalTo("friend", friendID);
query.equalTo("user", userID);
query.find({
success: function(results) {
},
error: function(error) {
}
});
or like this:
var query = new Parse.Query("Users");
query.get(objectID, { // Gets row you're trying to update
success: function(row) {
},
error: function(row, error) {
}
});
Is there any explanation for this clauses where they could come from? Does the .get Method results in where:{}? I am not sure...
Closing as sunsetting parse.com

Resources