I'm using Node.js and MongoDB with my database hosted on MongoHQ (Now compose.io). I have a general understanding document IDs are converted to hex strings but I can't figure out how to retrieve a document using its ID.
My document has the ID _id: ObjectId("53f13064b5a39cc69f00011b") as in that's how it's displayed in Compose's interface. When I retrieve the document by brute force, the ID is shown as _id: 53f13064b5a39cc69f00011b.
What do I use in Node.js to retrieve this document? The query:
systemData.find({_id: "53f13064b5a39cc69f00011b"}).toArray(function(err, data) {//do stuff}
returns an empty set but so does querying with an object ID object
systemData.find({_id: new ObjectID("53f13064b5a39cc69f00011b")}).toArray(function(err, data) {//do stuff}
What am I missing?
You should be able to use:
systemData.find({_id: ObjectID("53f13064b5a39cc69f00011b")})
No need for the "new" on the beginning.
Related
This is the thing I want to accomplish: I'm building a web shop. The web shop has a React Front-end. The front-end fetches 5 collections from Firestore and displays all the items from the collection array on the shop page. A user selects an item on the shop page. I send the item fields such as (price, name, quantity, id) to my express server and the server makes a checkout session of the item fields. The user goes to a Stripe checkout form and is sent back to my front-end by Stripe when the payment is complete. I listen for that event on my server and when then want to update the quantity field of the item in Firestore.
But how do I query Firestore for this item? Is there a way to query Firestore with only this id field (or name field)? Some something like:
db
.collection('collections')
.where('id', '===', 1)
Or do I need to save the document id (of the collection) as a field inside the item map and also send that to Stripe? Or is there a better way to do this? I can't find anything online about this.
Here is a screenshot of Firestore.
Please forgive my beginner question. I'm still learning React, Firestore and Node.js.
First be sure you are sticking to the Firestore terminology correctly. There are collections and there are documents.
Collections you access via a path such as:
collRef = db.collection("products")
collRef = db.collection("products").where("quanity_on_hand", ">", "0")
collRef = db.collection("products").doc("12345").collection("purchase_history")
The latter instance can also be accessed via collRef = db.collection("products/12345/purchase_history").
In all the above cases you will get back a CollectionReference.
Documents you access such as:
docRef = db.collection("products").doc("12345")
docRef = db.doc("products/12345")
This returns you a DocumentReference for the document whose ID is "12345" in the collection "products".
So for your code example above, you want to use docRef = db.doc("collections/1") to get back the DocumentReference for the item you are after. (Or, alternatively, you could use: docRef = db.collection("collections").doc("1")
If you stick with the code that you have above, you'd get back a CollectionReference then you'd need to fetch the data with .get(), then extract the resulting documents (that will just be a single document), then work with that. Oh...and you will need to put an "id" field into all of your documents because the document's ID value (the "name" of the document) is not part of the document by default so if you want to use .where("id", "==", "1"), then you need to add an "id" field to your document and populate it correctly.
If you go with docRef = db.doc("collections/1"), you are querying for the document directly and will get back a reference to just that one. No need for extra fields, nor extracting a single document from a result set.
I'm trying to get all the ids of all documents from a parsed collection without being charged for getting the document data. Will I be charged for receiving the data if I use this code below?
db.collection("owners").get().then(function(querySnapshot) {
querySnapshot.forEach(function(doc) {
console.log(doc.id);
});
});
This the database:
Yes, you will be changed a document read for each of documents in the collection. There's no way to do this without reading the documents.
How to get a list of document IDs in a collection Cloud Firestore?
My Cloud Firestore looks like this:
users
├────random_id_1───{name, email, ...}
├────random_id_2───{name, email, ...}
...
└────random_id_n───{name, email, ...}
I want to update a document of users given I have an unique identifier for it that is NOT the random id of the document (suppose, for example, the name is unique and I want to use it as identifier).
How can I update a document identifying it by a field of it?
Firestore can only update documents for which it knows the complete reference, which requires the document ID. On your current structure, you will have to run a query to find the document. So something like:
firebase.firestore().collection("users")
.where("name", "==", "Daniel")
.get()
.then(function(querySnapshot) {
querySnapshot.forEach(function(document) {
document.ref.update({ ... });
});
});
If you have another attribute that is unique, I'd always recommend using that as the IDs for the documents. That way you're automatically guaranteed that only one document per user can exist, and you save yourself having to do a query to find the document.
I currently have the following node:
Basically what I want is to search the registry by the uid parameter. What I can not understand is that they tell me that I should not do it by means of a query, so what would be the other way? I have tried with the following:
firebase
.database()
.ref('nuevosUsuario')
.child(user.uid)
.once('value')
.then(snapshot =>
console.log(snapshot.val())
);
pero me imprime en consola null
Thank you in advance, I'm new to firebase.
You JSON structure stores user information, where it stores the information for each user under a so-called push ID (a key generated by calling push() or childByAutoId()). You're trying to query this structure to find the user based on their UID, which is stored in a property for each user. The only way to do this is by using a database query, like:
firebase.database()
.ref('nuevosUsuario')
.orderByChild("uid")
.child(user.uid)
.once('value')
.then(snapshot => {
snapshot.forEach(userSnapshot => {
console.log(snapshot.val())
});
});
You need to perform a loop here, since there may be multiple nodes that have the correct value for their UID property.
If there can logically be only one node for each user under nuevosUsuario, it is better to store the user information under the user's UID as a key, instead of using a push ID.
So you'd get a structure like:
"nuevosUsuario": {
"SYFW1u808weaGEf3fW...": {
"appellido": "PRUEBA",
"correo": "..."
...
}
}
This has a few advantages:
There can only be one child node for each user, since keys are by definition unique in a collection.
You can now get the user given their UID without a query, which is both faster and simpler in code. As in: the code in your question would work for this structure.
i use sails js 0.12.14 with mongodb. if i try to get a document after insert the document the document is empty
Products.create(product).exec(function(err, createdProduct) {
Products.find({_id : createdProduct.id}).exec(function(err, foundProductAfterCreate) {
console.log(foundProductAfterCreate);
})});
Can anybody explain why the document is not available?
Update:
This is the correct code for me...
Products.create(product).exec(function(err, createdProduct) {
Products.find({_id : createdProduct[0].id}).exec(function(err, foundProductAfterCreate) {
console.log(foundProductAfterCreate);
})});
The doc you are querying for is literally the same one you already have
Products.create(product).exec(function(err, createdProduct) {
// handle the error...
console.log(createdProduct); // the full record
});
createdProduct is exactly the same object you would get if you queried by id.
If you do ever need to query by id, sails does a fairly comprehensive switch from _id which is the mongo standard, to id with no underscore. You would do that like this:
Products.findOne({id: createdProduct[0].id}).exec(function(err, foundAgain) { // etc
...no underscores anywhere unless you use .native for more basic mongo query access.