Firebase Cloudfirestore update elements in a collections - node.js

i'm using firebase functions with nodejs and cloudfirestore to build an API, now i have a problem, i have a collection an inside the collection an array of objects.
My goal is to update only a specific element without read the whole object and then push it again.
This is how my "order's collection" looks like:
"someRestaurantId":[{id:1,desc:"test",val:3000},{id:2,desc:"test",val:4000},{id:4,desc:"test",val:5000}]
My goal es only update id 2.
This is what i been trying:
Get the full list based on
const document = db.collection('orders').doc(req.params.restId);
Iterate and find the correct element, modify it and update it again.
await document.update(fullobject)
The problem is that i need something more easy to handle since there could be thousand of element inside that array.

Looking at described issue, I think you should use subcollection (sometimes called nested collection) for that. However from the description it is hard to tell what do you have now.
Firestore collection structure is always like this:
collection -> document -> fields and nestedCollections
than nestedCollection has the same structure, so you can nest whole structure how many times you want, but always collection contain only documents and each document contain only fields and collection.
In presented collection description array is directly in the collection or directly in document which both are impossible.
Anyway my idea is to structure it following way:
Collection orders containing docs of various restIDs
every docs (ex. "someRestaurantId") contain subcollection with name ex. "RestOrders"
in the subcollection will add documents with ids like (1,2,3 etc.)
every doc in subcollection will have fields desc, val
Collection Orders:
Document RestID_1:
Subcolection RestOrders:
Document 1: {val: 3000, desc: test}
Document 2: {val: 3000, desc: test}
...
Document RestID_2:
Subcolection RestOrders:
Document 1: {val: 3000, desc: test}
Document 2: {val: 3000, desc: test}
...
And now to update value of "RestID_1", order "id 2" you can use:
db.collection('Orders')
.doc('RestID_1')
.collection('RestOrders')
.doc('2')
.update( {val: 4000} )
In above solution you avoid reading and updating big array. You can update only one filed of one document in nested sub-collection.

Related

How to query field exist some document in firebase

I using firebase, nodejs and i have a question how to query field exist some document.
Example :
Collections : users => document : A with field {
....
is_correct: true
}
document : B with field {
.....
}
In my above example , i have two document in collection users. On document A i have field is_correct: true and on document B field is_correct not exist.
My collection users about 15.000 document and it have 50 document contain field is_correct: true
When i write code look like :
await firestore.collection('users').where('is_correct', '==', true).get();
it can get correct me 50 document. But i don't understand it can using index on field is_correct or not ? And it can query best performance ? I understand firebase can't get document if field undefined. It impart in case ? Please help ? Thanks you
For a simple query like
firestore.collection('users').where('is_correct', '==', true)
you don't need to configure any index, Firestore does it automatically.
As you mentioned, only documents where the given field exists can match the query.
And this is the case also for Not-equal (!=) and not-in queries: they exclude documents where the given field does not exist, as explained in the documentation.
Also, note that a field exists when it's set to any value, including an empty string (""), null, and NaN (not a number).
So, in conclusion, if you want to query for documents where is_correct is not true, you need to create this field in these documents with a value different than true.

Get multiple documents from collection using nodejs and mongodb

Hi I have two mongodb collections. The first one returns json data (array) and with the output of this, I want to return documents that match.
When I run Console.log (req.bidder.myBids) I get the following output:
[{"productId":"3798b537-9c7b-4395-9e41-fd0ba39aa984","price":3010},{"productId":"3798b537-9c7b-4395-9e41-fd0ba39aa984","price":3020},{"productId":"4c4bd71c-6664-4d56-b5d3-6428fe1bed19","price":1040},{"productId":"4c4bd71c-6664-4d56-b5d3-6428fe1bed19","price":1050},{"productId":"4c4bd71c-6664-4d56-b5d3-6428fe1bed19","price":1060},{"productId":"4c4bd71c-6664-4d56-b5d3-6428fe1bed19","price":1070},{"productId":"4c4bd71c-6664-4d56-b5d3-6428fe1bed19","price":1090},{"productId":"4c4bd71c-6664-4d56-b5d3-6428fe1bed19","price":1100}]
The productId has duplicates, I want to remove duplicates and then call a routine that finds all the products that match and output as json.
So far I have this code that only outputs one document, but cant figure out how to add the array of productId's and then fetch all corresponding products.
var agencyId = req.body.agencyId;
var productId = req.body.productId;
if (!validate.STRING(agencyId)) {
res.apiError(messages.server.invalid_request);
} else {
dbProduct.find({productId:{$in:['3798b537-9c7b-4395-9e41-fd0ba39aa984','4c4bd71c-6664-4d56-b5d3-6428fe1bed19']}
}).then(dbRes => {
console.log(dbRes);
Updated code and works with hard-wired productId and updated above code. Looking at how to get the array data and transpose replacing the hard-wired productId's
The $in operator is what you want. See the docs here: https://docs.mongodb.com/manual/reference/operator/query/in/

Get all documents whose property equals one of the elements in an array

I have a Post model that has a publisher property defined in its schema (I'm using Mongoose). The publisher property is a string that refers to a publisher's name.
I also have an array called sourceNames that holds all the different publisher names. I want to query my database for ALL the posts whose publisher matches any one of the array elements in sourceName. My current query looks like this:
const query = postModel
.find({ publisher: { $all: sourceNames } })
.limit(limit)
.skip(startIndex);
My query isn't returning anything when I exec it. Does anyone know if what I'm trying to do is possible in a single query (Rather than loop over sourceNames and make a query for each individual element?
Short
Just replace $all with $in
Expl
$all is trying to match an array with all elements in your array.
$in instead, tries to match a string or array with one in the array.

Firebase Invalid document reference. Document references must have an even number of segments

What is wrong with this query?
const db = firebase.firestore()
const query = db.doc(this.props.user.uid).collection('statements').orderBy('uploadedOn', 'desc').limit(50)
I get the following error:
Uncaught Error: Invalid document reference. Document references must have an even number of segments, but FrMd6Wqch8XJm32HihF14tl6Wui2 has 1
at new FirestoreError (index.cjs.js:346)
at Function.DocumentReference.forPath (index.cjs.js:15563)
at Firestore.doc (index.cjs.js:15368)
at UploadStatementPresentation.componentWillMount (UploadStatementPage.jsx:61)
at UploadStatementPresentation.componentWillMount (createPrototypeProxy.js:44)
at callComponentWillMount (react-dom.development.js:6872)
at mountClassInstance (react-dom.development.js:6968)
at updateClassComponent (react-dom.development.js:8337)
at beginWork (react-dom.development.js:8982)
at performUnitOfWork (react-dom.development.js:11814)
Since you haven't described what exactly you're trying to query, I'll just point out that all documents must be in a collection, without exception. So, if you say this:
db.doc(this.props.user.uid)
Firestore assumes that the string you're passing to doc() contains both the collection and document id separated by a slash. But this seems to be highly unlikely in your case. You need to determine which collection the uid is in, and use that first when you build the reference to the collection you want to query. Assuming that you do have a statements subcollection in the uid document, and that some other collection contains the uid document, you'll have to specify the full path like this:
db.collection('that-other-collection').doc(this.props.user.uid).collection('statements')
Of course, only you know the actual structure of your data.
If you want to get a collection of documents with querying, you don’t have to specify a document id. Below code should work in this case.
const query = db.collection('statements').orderBy('uploadedOn', 'desc').limit(50)
Or if you want to get the document, you can pass the document id to doc() method. In that case, the code should be.
const query = db.collection('statements').doc(this.props.user.uid)
For more details about querying firestorm data: https://firebase.google.com/docs/firestore/query-data/get-data?authuser=0
For others having this issue, make sure that no document reference has an empty string.
I had this issue when using a get method with uid input as below and forgot to check if uid is empty
private fun getFullRef(uid: String): CollectionReference {
return ref.document(uid).collection(FireContact.SUB_PATH)
}

mongodb querying logic mongoose and nodejs

I apologize beforehand if this is a repeat question but i could not find any and i am a beginner.
I am making a filter for documents of db.
lets say I want to query 8 fields of documents written in a object
filter={key1:{lowerlimit: 'value', upperlimit:'value'},
key2:{lowerlimit: 'value', upperlimit:'value'},
key3:{lowerlimit: '', upperlimit:'value'},
key4:{lowerlimit: 'value', upperlimit:''},
key5:[],
key6:['value','value'],
key7:['value','value','value'],
key8:['value']}
now how do i write the logic of query so that the fields whose value is not specified will not get query. if i query all the parameters as they are. no documents will be displayed because 'key5' is empty array and using $in on it will result in no documents.
You'd want to remove the key5 field from your query object when it's empty.
if (!filter.key5.length) {
delete filter.key5;
}

Resources