I want to get a collection of subCollections,
admin.firestore()
.collection(SCHEDULE_COLLECTION)
.doc(user)
.listCollections()
.then(collections => {
const cId = [];
collections.forEach(collection => {
});
return res.send(cId);
})
.catch(err => {
console.log(err);
return res.status(500).send(err);
});
I'm getting here ID,
Now I want to get the collections under
this object
How I can do it?
Thanks
Those are not subcollections. What you circled are fields in a single document. Just read build a reference to the document and read it like you normally would with get(). "events" and "foods" will be array type fields in the document snapshot.
const ref = admin.firestore()
.collection(SCHEDULE_COLLECTION)
.doc(user)
.collection(collection)
.doc(...)
.get()
You'll have to query the collection to get the list of documents if you don't know the document ID.
Related
I have a problem with getting data from the Firestore with a following structure
Here is how I get category collection:
app.get('/getProjectsNo', (request, response) => {
response.set('Access-Control-Allow-Origin', '*')
let orders = []
db.collection('companies').doc('renaultsomaca').collection('orders').get().then(snapshot => {
snapshot.forEach((doc) => {
orders.push(doc.data())
});
response.send(orders)
})
})
It gives me: orders list.But I need to get orders without using doc('renaultsomaca').Because I just need all orders not only renaultsomaca orders.
What you're describing is known as a collection group query, which queries across all collections with a specific name.
To get all documents from orders collections, no matter where they are in the database, you'd do:
const querySnapshot = await db.collectionGroup('orders').get();
querySnapshot.forEach((doc) => {
console.log(doc.id, ' => ', doc.data());
});
There is no way to specify the path to the orders collection, so if you have multiple types of orders that you want to query separately, you'll have to give them distinct names.
So this seems pretty straightforward but I cant seem to get it to work.I have a document in mongodb and i m using mongoose All i need to do is find user by id, get the document and delete one specified object from an array of objects. Here is the Structure:
report:[
{
asset_report_id:234,
name:'somethign,
},
{
asset_report_id:23,
name:'somethign,
},
{
asset_report_id:111,
name:'somethign,
}
]
I tried this :
User.findOne({_id: request.decodedTokenData.userId})
.exec()
.then(user=>{
const result = user.reports.find( ({ asset_report_id }) => asset_report_id === assetID );
console.log('IN FIND',result);
})
.catch(err=>console.log(err))
Now i do get the result which is great and i can delete but isn't there a method to do it with mongoose directly? More alongthe lines of plain mongo version of :
db.removeObject.update( {'_id':ObjectId("5c6ea036a0c51185aefbd14f")},
{$pull:{"reports":{"asset_report_id":234}}},false,true);
So the correct solution is:
await User.updateOne( {'_id':ObjectId("5c6ea036a0c51185aefbd14f")},
{$pull:{"report":{"asset_report_id":234}}},false,true)
since the data model contains "report" array
So I am creating an API in firebase and in the database there is a collection of universities. Inside this collection there are multiple documents of universities. In each document I've created a collection of users. So inside every university you can see the users that attend this uni.
What I want to do is everytime I make a request to the server by GET of api/user it shows (through authorization token) my details as a user.
I have created the function that requests the data of a user, by using the Bearer {token} but it seems that, when I console log the university ID is undefined. Inside the user document there is a field called uniId (the id of the university the user belongs and it is the same ID of the university document). I am using postman to make the API requests after I have created the Bearer token with another login function.
exports.getAuthenticatedUser = (req, res) => {
let userData = {};
db.doc(`/unis/${req.user.uniId}/users/${req.user.handle}`).get()
.then((doc) => {
if(doc.exists){
userData.credentials = doc.data();
return res.json(userData);
}
})
I understand that I need to change something in "req.user.uniId" because now that variable is undefined.
Any guidance on how I can approach this?
One option is to add a userhandle field to your documents so you can use a collection group query. Something like this:
exports.getAuthenticatedUser = (req, res) => {
let userData = {};
db.collectionGroup('users').where('userhandle', '==', req.user.handle)
.limit(1)
.get()
.then(function (querySnapshot) {
querySnapshot.forEach(function (doc) {
userData.credentials = doc.data();
return res.json(userData);
});
}).catch(function(error) {
console.log("Error getting documents: ", error);
})
}
Let us assume that we have two collections say "users" and "usersList"
Upon creating a new user document in users collection with following object
{username: Suren, age:31}
The function should read the above data and update other collection i.e. "usersList" with the username alone like below
{username: Suren}
Let me know the possibility
The code I have tried is
exports.userCreated =
functions.firestore.document('users/{userId}').onCreate((event) => {
const post = event.data.data();
return event.data.ref.set(post, {merge: true});
})
I have done it using below code
exports.userCreated = functions.firestore.document('users/{userId}')
.onCreate((event) => {
const firestore = admin.firestore()
return firestore.collection('usersList').doc('yourDocID').update({
name:'username',
}).then(() => {
// Document updated successfully.
console.log("Doc updated successfully");
});
})
If all you want to do is strip the age property from the document, you can do it like this:
exports.userCreated = functions.firestore.document('users/{userId}').onCreate((event) => {
const post = event.data.data();
delete post.age;
return event.data.ref.set(post);
})
I have a collection of some users (along with their contact numbers) registered in my node and mongodb app.
Now I have an array of contact numbers. I want to get an intersection of this array and the users in my app. How to do it, since I cannot take each number and check for it's existence in the database. Any help/link would be helpful. Thanks in advance.
You can use the $in operator. It would really help if you at least provided some code, like your schemas, previous attempts etc.
Here is an example of how to do ii assuming you are using mongoose, and have a user schema with a number property and an array of numbers.
User.find({ number: { $in: numbers } })
.then(function (docs) {
// do something with docs here;
})
.catch(handleErr);
This can be done simply using promises. I am assuming you have an array of contact numbers and a collection Users which has field contact number. The below function will get you the list of all the Users with contact numbers listed in the array. I am assuming that the User model is available and the contact array is being passed as a function argument. Basically this function will loop through the contact list array and find any user with that contact no in the user collection and return a promise. All the promises are being pushed into an array and the promise will be resolved only when all the async operations have completed resulting in either success or error.
// import User from User-model-defition
function getUsersByContact(contactArr) {
return new Promise((resolve, reject) => {
const data = [];
const errors = [];
contactArr.map(id => {
User.findOne({ contact_no : id })
.then(response => {
if (response.user) { //checking if the response actually contains a user object
data.push(response.user);
} else {
errors.push(response.error);
}
if (contactArr.length === data.length + errors.length) {
//this makes sure that the promise will be resolved only when all the promises have been resolved
resolve({ data, errors });
}
})
.catch(error => reject(error));
})
})
}