How to get a Fieldvalue only if other fieldvalues in the same document are true - reactjs

How to: If I want to retrieve a FieldValue (String) only if in the same document there is another field (boolean) which is true.
For Example: If I have a Document in Firestore which contains a Field: {name: "Some Name", active: true} and I only want the name to be retrieved if the field "active" is true. Is this possible?
Does this question make sense? Sorry, I'm a self-taught developer and I have difficulties to explain stuff as a coder. But I hope you guys can still understand what I want to achieve.

You can run query to filter out the documents you don't want. like:
query(collection(db, "users"), where("active", "==", true));
But if you want retrieve a single fieldvalue like "name" and filter out other value in same document like "active" is impossible. firestore only retrieve whole document.

Related

I need to use Mongoose to search with non-overlapping parameters?

I need some help using Model.find() in Mongoose.
I’ve added a boolean field isPrivate to a data model so users can specify if they want their entries to be publicly viewable, or viewable only by them. Here’s the current index function which returns all documents:
Snippet.find({})
.populate('addedBy')
.then(snippets => res.json(snippets))
.catch(err => {res.json(err)})
}
I need to modify this so that it returns all documents where isPrivate === false AND all documents where isPrivate === true if the current user ID matches the document’s field that logged the user ID when created. Any ideas? Making either of these queries is simple, but I need to make both of them.
I’m not sure how to use Model.find() with two sets of parameters. Is this possible?
Or is there a way to make two Mongoose queries and combine the results?
If I understand correctly what your requirements are, using the $or operator should help:
Snippet.find({
$or: [
{isPrivate: false},
{isPrivate: true, creatorField: currentUserId}
]
})
.populate('addedBy')
.then(snippets => res.json(snippets))
.catch(err => {res.json(err)}) }
This will return all documents where isPrivate is false, as well as all documents where isPrivate is true and the creator is the current user. (you'll of course have to adapt creatorField and currentUserId)
If however, you want to query on the populated field addedBy, you'll have to use the aggregation framework with the $lookup operator.

mongoose $literal in find method projection

I have a mongoose find method like this,
photo.find({},{
name:1,
src:1,
likes:{$literal:[]},
dislikes:{$literal:[]},
}).then(photos => ....)
what I want is, when I run the code likes and dislikes field must be an empty array for every record.
I try this way but not working.
Unsupported projection option: likes: { $literal: 1 }
Any idea to add default value for any field in find method ?
As per mongoose, document schema is constructed during its creation. So you can also edit the schema with a default value, so for every record, when it is created it will create likes, and dislikes with empty values.
You can also do this way, if you feel the schema control is not in your hands.
https://mongoosejs.com/docs/2.7.x/docs/defaults.html
photo.find({ 'name' : '1', 'likes': {$ne: []}})

How can I filter records by their ObjectID (_id) in Ag-grid

I'm using MongoDB to store my records and am using Ag-grid react to display them. The grid has several columns including the record's ObjectID (_id), name, type, etc. Using the filter agColumnTextFilter works for the name and type fields with the columnDef of:
{
headerName: 'Column Name',
field: 'name',
filter: 'agTextColumnFilter',
},
which then leads to this query setup (using the contains filter option):
case "contains":
qp[fieldName] = new RegExp(['.*', user input string, '.*'].join(''), 'ig');
this logs the correct query:
"query db { name: /.*query string.*/gi }"
and the proper rows are displayed. Since the displayed _id is a string as well I tried something similar:
{
headerName: 'ID',
field: '_id',
valueGetter: (params) => {
let id = params.data._id;
return id.slice(id.length-5); //only display last part of ID instead of entire thing
},
filter: 'agTextColumnFilter',
},
Using the same contains logic as above the following query is logged to the console:
query db { _id: /.*_id segment.*/gi }
However, no rows are returned in this case (even though there should be rows returned). Do I need to use different logic or is there a problem with this current logic? Any advice is appreciated.
Edit: Turns out even though the ID displays as a String a cast of the string to an ObjectID is needed:
qp[fieldName] = new ObjectID(_id string)
Problem with this is searching for part of a specific ID won't work because it's not a valid ID. Searching for a full ID works but isn't ideal either. If anyone has any ideas on how I can filter just part of the ID I'd appreciate it.
You can probably set a valueFormatter on the column that displays the partial ObjectId. The filtering will be done using the full ObjectId.

Firestore to query by an array's field value

I'm trying to run a simple query, where I search for a document that contains a value inside an object array.
For instance, look at my database structure:
I want to run a query similar to this:
db.collection('identites').where("partyMembers", "array-contains", {name: "John Travolta"})
What is the correct way to achieve this, is it even possible with Firestore?
Thanks.
As Frank has explained in his answer it is not possible, with array-contains, to query for a specific property of an object stored in an array.
However, there is a possible workaround: it is actually possible to query for the entire object, as follows, in your case:
db.collection('identites')
.where(
"partyMembers",
"array-contains",
{id: "7LNK....", name: "John Travolta"}
)
Maybe this approach will suit your needs (or maybe not....).
The array-contains operations checks if an array, contains a specific (complete) value. It can't check if an array of objects, contains an item with a specific value for a property.
The only way to do your query, is to add an additional field to your document with just the value you want to query existence on. So for example: partyMemberNames: ["John Travolta", "Olivia Newton"].
If you want to extract name: "John Travolta" from "partyMembers" array in a document. you can achieve this by some similar approach in which you can loop through all arrays in a document to find this name.
const [names, setNames] = React.useState([])
const readAllNames = async() => {
const snapshot = await firebase.firestore().collection('identites').doc(documentID).get()
const filterData = snapshot.data().question.map(val => val.name === "John Travolta" ? val : null)
setNames( filterData.filter(e=>e) );
}
This technique is used in perticular Document as we are giving .doc(documentID) This way you can get all the arrays having name: "John Travolta" in names constant.

MongoDB: Query and retrieve objects inside embedded array?

Let's say I have the following document schema in a collection called 'users':
{
name: 'John',
items: [ {}, {}, {}, ... ]
}
The 'items' array contains objects in the following format:
{
item_id: "1234",
name: "some item"
}
Each user can have multiple items embedded in the 'items' array.
Now, I want to be able to fetch an item by an item_id for a given user.
For example, I want to get the item with id "1234" that belong to the user with name "John".
Can I do this with mongoDB? I'd like to utilize its powerful array indexing, but I'm not sure if you can run queries on embedded arrays and return objects from the array instead of the document that contains it.
I know I can fetch users that have a certain item using {users.items.item_id: "1234"}. But I want to fetch the actual item from the array, not the user.
Alternatively, is there maybe a better way to organize this data so that I can easily get what I want? I'm still fairly new to mongodb.
Thanks for any help or advice you can provide.
The question is old, but the response has changed since the time. With MongoDB >= 2.2, you can do :
db.users.find( { name: "John"}, { items: { $elemMatch: { item_id: "1234" } } })
You will have :
{
name: "John",
items:
[
{
item_id: "1234",
name: "some item"
}
]
}
See Documentation of $elemMatch
There are a couple of things to note about this:
1) I find that the hardest thing for folks learning MongoDB is UN-learning the relational thinking that they're used to. Your data model looks to be the right one.
2) Normally, what you do with MongoDB is return the entire document into the client program, and then search for the portion of the document that you want on the client side using your client programming language.
In your example, you'd fetch the entire 'user' document and then iterate through the 'items[]' array on the client side.
3) If you want to return just the 'items[]' array, you can do so by using the 'Field Selection' syntax. See http://www.mongodb.org/display/DOCS/Querying#Querying-FieldSelection for details. Unfortunately, it will return the entire 'items[]' array, and not just one element of the array.
4) There is an existing Jira ticket to add this functionality: it is https://jira.mongodb.org/browse/SERVER-828 SERVER-828. It looks like it's been added to the latest 2.1 (development) branch: that means it will be available for production use when release 2.2 ships.
If this is an embedded array, then you can't retrieve its elements directly. The retrieved document will have form of a user (root document), although not all fields may be filled (depending on your query).
If you want to retrieve just that element, then you have to store it as a separate document in a separate collection. It will have one additional field, user_id (can be part of _id). Then it's trivial to do what you want.
A sample document might look like this:
{
_id: {user_id: ObjectId, item_id: "1234"},
name: "some item"
}
Note that this structure ensures uniqueness of item_id per user (I'm not sure you want this or not).

Resources