MongoDb: find(), property of document matches one value of given array - node.js

So I'm making a search bar in my app and I'm using mongodb to fetch the results.
The situation is as following:
When the _group property (which is an ObjectId) of the post document is equal to one of the values in the exampleArray I want this post to be included in my end result. How would I do this?
const exampleArray = ['ObjectId1', 'ObjectId1', 'ObjectId1'];
const posts = await Post.find({_group: exampleArray })

The query will need to use the MongoDB $in operator, which is used to compare a field against a list of values.
Try the following:
posts = await Post.find({_group: { "$in" : exampleArray } })

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.

How to count documents in mongodb/express

I have a express API and I wan't to return the documents that match the query params, as well as the number of documents.
I have the following query, and I wan't to return the following object.
const property = await Property.find(query1);
res.json({ 'results:': property.countDocuments(), property });
I get the following error
property.countDocuments is not a function
Just do this:
const property = await Property.countDocuments(query1);
find returns an array of documents, so you can just use, .length property.length

Firestore: Searching the element inside document array if it exists or not

I am having collection with some documents. Each document contains some arrays with strings. I want to know whether given string is there inside the specific document array. I have seen queries to find the documents by using array contains. But I have the document I just want to query whether the string exists inside that document array or not?
var dbRef = dbConnection.db.collection('posts').doc(req.body.post_id);
dbRef.where('likes', 'array-contains', req.body.user_id).get()
.then(data => {
console.log(data);
})
.catch(err => {
console.log(err);
})
I have a document with specific id. I know the document id. That document contains array named as likes. That array will store some strings. I want to know the whether the string exists or not inside that array or not? I am getting the following error
TypeError: dbRef.where is not a function
Then I tried without giving document id. It worked. It returned the documents. But I want to search inside the document array
Your dbRef points to a (single) document, and you can't query a document.
If you want to query the documents in the posts collection, you're looking for:
var dbRef = dbConnection.db.collection('posts');
dbRef.where('likes', 'array-contains', req.body.user_id).get()
...
You can query for both document ID and array contains with:
db.collection('books').where(firebase.firestore.FieldPath.documentId(), '==', 'fK3ddutEpD2qQqRMXNW5').get()
var dbRef = dbConnection.db.collection('posts');
dbRef
.where(firebase.firestore.FieldPath.documentId(), '==', req.body.post_id)
.where('likes', 'array-contains', req.body.user_id).get()
...
Alternatively, you can simply read the document with your original code, and then check client-side whether the array still contains the field:
var dbRef = dbConnection.db.collection('posts').doc(req.body.post_id);
dbRef.get()
.then(doc => {
if (doc.data().likes.indexOf(req.body.user_id) >= 0) {
... the post is liked by the user
}
})
.catch(err => {
console.log(err);
})

Could not find the right value using the MongoDB aggregate function

I need to fetch value as per some user input using MongoDB aggregate function but in my case, I could not return the right value. Here is my code:
var cname=req.body.cname;
var id=req.body.id;
Company.collection.aggregate([
{ $match:{$and:[{cname:cname},{_id:{$ne:id}}]}}
])
I need to fetch those value by comparing the cname value and _id is not equals to the given id. But In my case, the user input id value is fetching where I need other the user input id documents.
You need to change the query as mentioned below:
Company.collection.aggregate([
{ $match:{$and:[{cname:cname},{$ne:{_id:id}}]}}
]);
See if it helps!
You can try below code.
const ObjectId = require('mongodb').ObjectId;
Company.collection.aggregate([
{$match : {$and: [{cname:cname},{$ne:{'_id':ObjectId(id)}}]}}
]);

node.js: compare array of ObjectIds with a string object id or an array of string ObjectIds

My Schema is:
var schema = new Schema({
players: {
type: [Schema.Types.ObjectId]});
I'm using Promises. My simple query to fetch the collection by id is:
MyModel.findById(id).exec()
.then(function (doc) {
//here I'm getting my doc
})
.catch(next)
I'm getting my document but the problem is here I'm getting an array of ObjectIds and I want to compare this array of ObjectIds with an ObjectId which I have in the string form. In one case I want to find the index of this string id in that array of ObjectIds.
I tried by lodash like
var index = _.indexOf(doc.players, idInStringForm);//getting -1 as response
also tried with
var index = _.indexOf(doc.players.toString().split(","), idInStringForm);//it is working
but when I needed to take union of ObjectIds' arrays the above logic fails for example:
var arrayOfIds = _.union(doc.players.toString().split(","), stringArrayOfIds);
the above is not working because when doc.players is empty the arryaryOfIds also contains " " which fails my one of queries.
Does we have any better/common solution for the above cases or we need to go with if-else check?
You can filter out any empty strings before checking the union of the array and the id.
function removeEmptyStrings(value) {
return value != "";
}
array = array.filter(removeEmptyStrings);
Wherever the array value is equal to an empty string it will remove it from the array.
See the documentation for the filter method here: Filter
Why not Array.prototype.map and then union?
_.union(doc.players.map((player) => player._id), stringArrayOfIds)

Resources