How to update this firestore document field using cloud functions? - node.js

Im new to firebase, firestore and cloud functions. How do I update the this filed called "status" based on a field called "LastUpdatedAt"
exports.hello = functions.firestore.document("RealtimeData/{anyMachine}/Params/{anyParams}")
The field "LastUpdatedAt" is inside {anyParams}: It looks like
LastUpdatedAt: 1606844285038
After conversion from timestamp
LastUpdatedAt: 1/12/2020 23:8:5
How do I write a cloud function to compare this "LastUpdatedAt" with the present time and if the time difference is greater than 15 then the 'status' should be set to offline else it should be online.

If you want to update a single field in a document then first you should retrieve the document through document ID then you can perform the update function while specifying the field.
For more information you can refer to the documentation and stackoverflow answer, where a brief description about node js SDK for Cloud Firestore has been discussed.

Related

How can I select specific fields using the firestore modular api

In the <= V8 Firestore API I could query a set of documents and extract a subset of fields with code like the following:
const membersRef = db.collection('members');
const snapshot = await membersRef.select('First', 'Last').get();
With the new modular api I can do the following:
import { collection } from 'firebase/firestore';
const membersRef = collection(db,'members');
// how to select only First and Last from members ?
I can't find a select() function to specify fields in the new api. How can this be done using the V9 modular api?
I know I can read the entire collection and use .map()/.forEach to reduce the fields but I have some large fields I would rather not query unless I need them for a specific document. The use of select to have the server pull out only the fields needed is useful.
The client-side SDKs for Firebase don't have a select method/function, but always retrieve full documents. So the select method didn't exist in the v8 CollectionReference or Query classes, nor does it exist as a top-level function in the v9 modular SDK.
There is a select() method in the Admin SDK for Node.js, but that one still works as a method on CollectionRefence as far as I can tell.

Firestore function to track new writes of documents and limit the count of all documents

When using Firestore database and Firestore functions, I am trying to achieve a way to keep documents count of a specific collection limited (For example, I don't want the collection to have more than MAX_COUNT documents).
This is the template of what I want to achieve (a Javascript script in index.js):
exports.docAdded = functions.firestore.document('myCollection/{docID}').onWrite((change, context) => {
if (!change.before.exists) {
// New document Created - check total number of documents in myCollection
//- Delete old documents in case of size>MAX_COUNT
}
});
Any help is appreciated !
There isn't a function developed yet, that supports the tracking of the number of documents in a collection. However, there are some alternatives and methods that you can give it a try, to help you achieve this limitation goal that you want.
I would recommend you to take a look at the below articles and posts from the Community, that might help you and provide some ideas on how to achieve this.
FR: Firestore collection count feature #932 - information about a feature request for this to be implemented in the future.
Cloud Firestore collection count
How do you force a Firestore client app to maintain a correct document count for a collection?
Let me know if the information helped you!

Running an Azure function app each time a CosmosDB document is created and updating documents in a second collection

I have a scenario, where we have items save in one documentDb collection e.g. under /items/{documentId}. The document looks similar to:
{
id: [guid],
rating: 5,
numReviews: 1
}
I have a second document collection under /user-reviews/{userIdAsPartitionKey}/{documentId}
The document will look like so:
{
id: [guid],
itemId: [guidFromItemsCollection],
userId: [userId],
rating: 4
}
Upon uploading of this document, I want a trigger to be fired which takes as input this new user rating document, is able to retrieve the relevant document from the items collection, transform the items document based on the new data.
The crux of my problem is: how can I trigger off a document upsert, and how can I retrieve and modify a document from another collection, all within a Funciton App?
I've investigated the following links, which tease at the idea of Triggers being possible on the CosmosDB, but the table suggests we can't hook up a trigger to document DB upload.
https://learn.microsoft.com/en-us/azure/azure-functions/functions-triggers-bindings
https://learn.microsoft.com/en-us/azure/azure-functions/functions-bindings-documentdb
If it's not possible to set up directly, my assumption is I should have a middle tier service handling the upsert (currently using DocumentClient from client side), which can kick off this processing itself, but I like the simplicity of the serverless function apps if possible.
Operations are scoped to a collection. You cannot trigger an operation in Collection B from an event in Collection A.
You'd either need to implement this in your app tier (as you suggested) or... store both types of documents in the same collection (a common scenario). You might need to add some type of doctype property to help filter your queries, but since documents are schema-free, you can store heterogeneous documents in the same collection.
Also: You mentioned an Azure Function. Within a function, there's nothing stopping you from making multiple database calls (e.g. when something happens in collection a and causes your function to be called, your function can perform an operation in collection b). Just note that this won't be transactional.
I know this is a pretty old question.
The Change Feed was built for this exact scenario.
In today's Azure Portal, there's even a menu option in the CosmosDB blade that allows you to create and trigger Function based on changes in one collection which allows you to detect and react to changes - i.e. to create a document in another collection.

update handler function to save timestamp in couchDB

I am looking to update each document inserted in a couchdb database with the current timestamp.I have referred the document_update_handler feature which can update individual documents.But what i see from the documentation is that an explicit POST/PUT request to the handler function needs to fired along with docid ,something like this:
http://127.0.0.1:5984/my_database/_design/my_designdoc/_update/in-place-query/mydocId.
What i am looking for is a solution that will automatically create new field with the current timestamp just before a new record is inserted.(I am using lightcouch API on the client side to persist a document).
Any help is appreciated.

what's the best way to bind a mongodb doc to a node.js html page

In past with my PHP / Rails - MYSQL apps I've used the unique ID of a table record to keep track of a record in an html file.
So I'd keep track of how to delete a record shown like this (15 being the ID of the record):
Delete this record
So now I'm using MongoDB. I've tried the same method but the objectID ._id attribute seems to be a loooong byte string that I can't use conveniently.
What's the most sensible way of binding a link in the view to a record (for deletion, or other purposes or whatever)?
If the answer is to create a new id that's unique for each document in the collection, then what's the best way to generate those unique id's?
Thank you.
You could use a counter instead of the ObjectID
But this could create a problem when inserting a new document after you deleted a previous one.
See this blog post for more detail info on Sequential unique identifiers with Node.js and MongoDB.
Or you could use the timestamp part of the ObjectID:
objectId.getTimestamp().toString()
See the node objectid docs

Resources