How to actually query data from Firestore with GeoFirestore? - node.js

I'm trying to query documents near a given point in given radius in Firestore with using GeoFirestore for my node.js project. Firstly, I have a document in the database in this format:
My query code is like this:
// Create the GeoFirestoreQuery object
const geoQuery = geoFirestore.query({
center: new firebase.firestore.GeoPoint(latitute, longitude),
radius: 5,
query: (ref) => ref.where("d.available", "==", true)
});
The thing is that, I cannot figure out how to get the document from the query. I tried the code below, but it simply is not called at all.
// Fetch the nearest couriers
const onKeyEnteredRegistiration = geoQuery.on("key_entered", function(key, document, distance) {
console.log(key);
});
How can I return the document? What I am missing? Is my query and database structure matches? Is there any missing fields or issues? Or should I use another query instead of "key_entered"? Thanks for any help in advance.

I found the issue, it was about the database structure. I changed my structure as shown below and now it works perfectly.

Related

Is there a way to filter through data based on if a search query is present in the string in mongodb?

I have data that looks like this in my mongoDB atlas database:
object: {
keywords: ['Homelessness', 'Food', 'Poverty']
}
I'm creating a filtering component for my MERN stack website and wanted to add a search feature for keywords like these that are present in each object in the database. If a search query was Homelessness for example, then the object above would show up since it has Homelessness as one of its keywords. But say for example I enter Homeless as a search query, the ones with Homelessness won't pop up because Homeless =/= Homelessness. Is there a way to somehow find if the search query is within a string inside an array which is all inside a json object?
Here is what I tried so far which gets the result I described in the situation above:
const getFilteredProjects = async (req, res) => {
// Initializing request object that will be sent to retrieve DB information
var request = {}
if (req.query.keywords !== '') {
request["keywords"] = req.query.keywords
}
console.log(request)
const projects = await Project.find(request).sort({ assignment_type: 1 })
res.status(200).json(projects)
}
How can I somehow access each string inside the keywords array and see if the search query is present in it? Is that possible with mongodb or would I have to somehow do it through javascript? If that's the case I'm not sure how I could do that, I would appreciate it if I could get some help.

List All Docs with #ibm-cloud/cloudant

So recently IBM deprecated #cloudant/cloudant and have moved on to #ibm-cloud/cloudant. I was in the process of doing a todo app to learn Cloudant along with some other things and so had to migrate to the new package.
As you can see from my Cloudant dashboard, I have a database with name "todo-vue-hapi" and there are 3 docs in the db. According to the migration docs to list all the documents before you would use db.list now you should use service.postDesignDocs so I connected everything and used the following code:
const response = await db.postDesignDocs({
db: 'todo-vue-hapi',
})
This gives back a response object with the following result property:
{result: { total_rows: 0, offset: 0, rows: []}
The 3 docs are not there! I'm wondering how I can query everything in the database "todo-vue-hapi". Help with this issue would be greatly appreciated.
The postDesignDocs function only returns design documents, which are special Cloudant documents containing index definitions.
To return all documents in a database you need to use the _all_docs API endpoint which is implemented as the postAllDocs function:
const response = await db.postAllDocs({
db: 'todo-vue-hapi',
includeDocs: true,
limit: 10
})
This should return you all documents in the database, including regular and design documents.

Is there a native way to get MongoDB results as object instead of array?

Checked couple of old similar questions but no luck in finding the right answers.
I have a mongo query that uses await/async to fetch results from the database, So the code looks like this :
(async () => {
//get connection object
const db = await getDatabaseConnection("admindb");
//get user data object
const configResponse = await db.collection("config").find({}).toArray();
//prints results
console.log("Successfully Fetched Configuration", configResponse);
})();
The above code works fine, just that it returns me an array of elements since I have used the .toArray() method.
Sample Result:
[
{
_id: "6028d30db7ea89f74df013d9",
tokenize: false,
configurations: { theme: {} }
}
]
Is there a NATIVE WAY (not looking forEach responses) to get result as an object since I will always have only one document returned. I have multiple queries that returns only one document, Hence accessing using the 0th index everytime did not seem the right way.
I am thinking if the findOne() will help you.
Check this out docs
await db.collection("config").findOne({});
Here are some examples

Watch MongoDB to return changes along with a specified field value instead of returning fullDocument

I'm using watch() function of mongo to listen to changes made to a replicaSet, now I know I can get the whole document (fullDocument) by passing { fullDocument: 'updateLookup' } to the watch method,
like :-
someModel.watch({ fullDocument: 'updateLookup' })
But what I really want to do is, get just one extra field which isn't changed every time a new update is made.
Let's say a field called 'user_id', currently I only get the updatedFields and the fullDocument which contains the 'user_id' along with a lot of other data which I would like to avoid.
What I have researched so far is Aggregation pipeline but couldn't figure out a way to implement it.
Can anybody help me figure out a way to this?
Thanks everyone for suggesting, as #D.SM pointed out I successfully implemented $project
Like this :-
const filter = [{"$match":{"operationType":"update"}}, {"$project":{"fullDocument.user_id": 1, "fullDocument.chats": 0, "fullDocument._id": 0, "fullDocument.first_name": 0, "fullDocument.last_name": 0 }}];
Then passed it to watch() method
Like:-
const userDBChange = userChatModel.watch(filter, { fullDocument: 'updateLookup' });
Now I'm only getting user_id inside fullDocument object when the operationType is update hence reducing the data overhead returned from mongo
Thanks again #D.SM and other's for trying to help me out ;)

How to get the defined indexes from Mongoose

I have been trying to find out the indexes which are already created via MongoDB manually( I have created 2d sphere indexes for two fields via mongobooster and creating one via schema by defining it). Now if i run this query in mongodbooster
db.collectionname.getIndexes();
It results me the 3 documents with name.key and which indexes i have used. I want to perform this same operation in mongoose i can't find a equivalent query for the same. I tried this
const indexes = OrderSchema.indexes();
console.log('index:', indexes);
But it gives me only one index which i have defined in schema that is _id i need two other fields as well which contains 2d-sphere index how can i get that too. What am trying to achieve here is if 2d sphere indexes are already created don't create an index else create an index that's all am trying to achieve here. Any help is appreciated Thanks
Yeah, you can't do it with a schema. You will need to create the model first, and then you can do something like this:
Order.collection.getIndexes({full: true}).then(indexes => {
console.log("indexes:", indexes);
// ...
}).catch(console.error);
If you dont have access to mongoose model, but the mongoose connection was created and you need to get the indexes from a collection you can access by this way:
const mongoose = require('mongoose');
mongoose.connect('myConnectionString', { useNewUrlParser: true }).then(() => {
getIndexes();
});
const getIndexes = async () => {
const indexes = await mongoose.connection.db.collection('myCollection').
indexes.forEach(function (index) {
console.log(JSON.stringify(index));
});
};

Resources