Insert mongodb document at specific time - node.js

I want to know if there’s a way to insert Data in database in a specific moment,
Exemple:
I want to send a text to the Database in 3 hours => As soon as i click on my button in my client side i want the document to be created in 3 hours.
Is it possible to do something like this ?

you can simply use setTimeOut like this.
let time = 60000 * 60 * 3;
function myFunc(arg) {
console.log(`arg was => ${arg}`);
}
setTimeout(myFunc, time, 'funky');
or use cronjob like this npm https://www.npmjs.com/package/node-cron

I don't think it's a good way to create documents. I don't know your problem, but I would solve it differently.
You could create the document when the button is clicked. But, you'll add a new property in your document like active_at that will hold a date value (timestamp or other). This value will be always current date + 3 hours. In your application, after that, you'll have to select/get documents where active_at is before the current date. This way, you'll have only the documents created at least 3 hours ago.

You can use setTimeout function in nodejs backend:
function myFunc(arg) {
//Insert text to mongodb
}
setTimeout(myFunc, 10800000); //myFunc will be called after 3 hours (10.8000.000 ms)
You can find more detail about setTimeout function here: https://nodejs.org/api/timers.html#timers_settimeout_callback_delay_args

Related

Firebase how to read latest children node?

I'm new to firebase and currently I'm still trying to learn how to get the latest children node based in this RTDB. My nodeMCU will send new data periodically so I'm trying to get the latest node when its added and the value of that node. Can you provide with a sample code for me to understand better? And if possible please explain like I'm 5. Thank you and have a good day.
From what I understand you have an Arduino module that is going to be constantly introducing data into your database.
What you want is to be able to read the value shown in the image as MQ7 every time a new value is added.
If this is the case there are different ways to obtain it.
The first and most common one would be to use the firebase Child Added event. With this event you can handle the data entered every time there is an addition to the reference to the database.
Using this event you would have a set of all the values entered in your reference and with each addition automatically (In Real Time) this set would be updated.
Taking your image as an example, the query code would be something like this (JS):
dbRef.child("Sensor MQ7").on("child_added", (snap) => {
for (i in snap.val()) {
const value_MQ7 = snap.child(i).child("MQ7").val()
// Do what you want with the value
console.log(value_MQ7)
}
})
If you don’t want to have that set with all the values entered in your reference, the best option would be a new function that returns only the value you are requesting, that is, a function that returns the MQ7 value of the last object entered in your reference sensor MQ7.
The query code would be something like this (JS):
const query = dbRef.child("Sensor MQ7").orderByKey().limitToLast(1);
query.get().then((snap) => {
for (i in snap.val()) {
// Do what you want with the value
const value_MQ7 = snap.child(i).child("MQ7").val()
console.log(value_MQ7)
}
})

Saved Search with Time Criteria

Use-Case : I am having an Integration in place that creates multiple Vendor Bills in Netsuite for every 5 minutes. I want to export the vendor bills created in those time to FTP. For that I need to create a saved search that can preview vendor bills created in past five minutes. Do we have any criteria in Netsuite Save Search to accomplish that ?
Please advise.
A Netsuite inconsistency.
I keep a snippet for this.
function toNSLegalDatetime(date){
var formatted = <string>format.format({value:date, type:format.Type.DATETIMETZ});
return formatted.replace(/(:\d{2}):\d{2}/, '$1');
}
Then you can do:
const lastDT = new Date(Date.now() - 5*60000)); // 5 minutes ago
search.create({
type:'vendorbill',
filters:[
search.createFilter({name:'datecreated', operator:search.Operator.ONORAFTER, values:toNSLegalDatetime(lastDT)}),
...
BUT
timing like this is very tricky because small delays in timing could cause you to miss transactions. If you can keep track of the last internalid reported your next search could just use that and it wouldn't matter what the lag was.
search.createFilter({name:'internalidnumber', operator:search.Operator.GREATERTHAN, values:lastIdReported})

Prob find latest collection

I don't find much information about this problem to solve.
On my mongodb I create a collection every 60 seconds with the name "test "+ date.now(). So far everything works ok. It creates me different collections with the name test XXXXXX1, test XXXXX2 etc.
I have problems with the mongoose.find() method. I can't find my last created collection.
let test = mongoose.model('test' + date.now(), Schema);
test.find({}, function (err, response) {});
How do I find the latest collection in stream? Thank you!
Mongo ,By default , does not support sequence .
for that purpose you're going to have to add specific field for sorting or sort your fields based on your current field properties.
After that you have to use .sort() cursor method :
Collection.find().sort([...]);
Read this article for more info

Use an array of values to query Firestore and setup a snapshot listener

Here is my problem:
I have a firestore collection that has a number of documents. There are about 500 documents generated/updated every hour and saved to the collection.
I would like to query the collection and setup a real-time snapshot listener for a subset of document IDs, that are provided by the client.
I think maybe I could to something like this (this syntax is likely not correct...just trying to get a feel for if it's even possible...but isn't the "in" limited to an array of 10 items? ):
const subbedDocs = ["doc1","doc2","doc3","doc4","doc5"]
docsRef.where('docID', 'in', subbedDocs).onSnapshot((doc) => {
handleSnapshot(doc);
});
I'm sorry, that code probably doesn't make sense....I'm still trying to learn all the ins and outs of Firestore.
Essentially, what I am trying to do is take an array of ID's and setup a .onSnapshot listener for those ID's. This list of IDs could be upwards of 40-50 items. Is this even possible? I am trying to avoid just setting up a listener on the whole collection and filtering out things I am not "subscribed" too as that seems wasteful from a resources perspective.
If you have the doc IDs in your array (it looks like you have) you can loop over them and start a listener during that:
const subbedDocs = ["doc1", "doc2", "doc3", "doc4", "doc5"];
for (let i = 0; i < subbedDocs.length; i++) {
const docID = subbedDocs[i];
docsRef.doc(docID).onSnapshot((doc) => {
handleSnapshot(doc);
});
}
It would be better to listen to a query and all filtered docs at once. But if you want to listen to each of them with a explicit listener that would do the trick.
As you've discovered, Firestore's in operator only allows up to 10 entries in the array. I'm also guessing you've added the docID as a field in the document, since I don't believe 'docID references the actual documentid.
I would not take this approach, because of the 10-entry limitation. What I would do is, as the client is selecting documents to follow, set a field (same in each document) to a unique Id for the client, so your query completely avoids the limitation. You can allow an unlimited number of Client listeners (up to implementation limits of Firestore) if you add that client ID into an array (called something like "ListenerArray") [again, as the client is selecting them]. Your query would be more like:
docsRef.where('ListenerArray', 'array-contains', clientID).onSnapshot((doc) => {
handleSnapshot(doc);
})
array-contains checks a single value against all entries in a document array, without limit. Every client can mark any number of documents to subscribe to.

Mongoose/MongoDB batchSize(30) still returning all results

The following query returns all my users. I was hoping it would be batched.
statics.findAllUsers = function findAllUsers(callback) {
this.find({}, callback).batchSize(30);
};
batchSize() instructs the driver to retrieve a certain number of items per time. It'll still get everything from the DB, only a batch at a time.
To make it clearer: If you use batchSize(30) then it'll ask for 30 items then, when you need the 31st, it'll query the next 30 and so forth.
If you need only that number of items, then use limit() (and offset() to set which is the first item)
Docs: http://docs.mongodb.org/manual/reference/method/cursor.batchSize/

Resources