How to remove element from array in mongoose? - javascript

Document:
{
reportId:6dgda82,
items:[],
}
I fetched the document using db.collection.findOne() and used document.items.push() to insert a new value and used document.save(),this was updated in the database.
But when i want to delete an item , deleted the item using javscript and used document.save() but the database is not updating.
Why ??
EDIT : I came to know about the $pull feature,
but why does inserting work when deletion is not working the other way.

Related

How can I access the child of a unique key in Firebase?

I am trying to access the child value of a unique key value (that had been "pushed") within Firebase. Currently, my database looks like this: I want to access the value of "emailOfUser"
I am very new to Firebase so I am not familiar with the functions. Currently, this is my method of obtaining other values for a different section of the database:
Thank you so much for any feedback!
I've tried different methods to accessing this data within the Firebase, but I cannot get it to work/the methods I were using were outdated. I also tried to "update" the Firebase instead of "pushing" the values to prevent a unique key from generating, but it simply overwrote my current data rather than appending something new.
If you want to load all the users who voted and print their emails, you can do that with:
get(child(dbref, 'usersWhoVoted')).then((snapshot) => {
snapshot.forEach((childSnapshot) => {
console.log(childSnapshot.key, childSnapshot.val().emailOfUser);
});
})
Note that your current structure allows a user to vote multiple times. If you want to only allow them to vote once, use some identifier of the user as the key in your database structure:
userVotes: {
"uniqueIdOfUser1": "valueTheyVotedOn",
"uniqueIdOfUser1": "valueTheyVotedOn",
...
}
Now each user can by definition only vote once, If they vote again (assuming your security rules allow that), their new vote will simply replace the existing vote.

How to only read changes in firebase realtime database

I have a database collection with readings, each new reading needs to be checked if it's out of the ordinary, if it is, there needs to be an alert sent.
So i'm using db.ref('collection').on('child_added', (child => { check(child); });
The problem with the .on function is that when the listener is added, all previous data is also read.
So how do i read a collection that only reads the changes in the database, also when the listener is first added? Or if that doesn't work, how do I differentiate the already added data with the new data?
The Firebase database synchronizes the state of whatever query or reference you attach your listener to. There is no option to only get new nodes built into the API.
If you want only new nodes, you will have to:
Ensure each node has an associated timestamp or order. If you're using Firebase's built-in push() keys, those might already serve that function.
Know what "new" means to the client, for example by either keeping the last timestamp or push key that it saw.
And then use a query to only request nodes after the stores timestamp/key.
So for example, if you only want to read nodes that are created after the moment you attach the listener, you could do something like this:
let now = db.ref('collection').push().key; // determine current key
db.ref('collection').orderByKey().startAt(now).on('child_added', ...)

Retrieve data from multiple documents from Firestore

I tried a lot of times but I am still not able to retrieve data from multiple documents, The below screenshot shows that I have 3 documents in my collection and my question is how to retrieve data from each of them.
I used foreach loop to loop through all the documents but I don't know how to retrieve data from id RoKQBRcuaVfcGPKNswbx or id Y8KbSQHcuxctJCJ1lWYH because it auto retrieve the data of the last id.
I really need your help, please.
Thank you.
The snapshot object contains all the 3 documents in your collection. You must iterate over all and render data to your HTML as explained below.
db.collection("Policies List").get().then((snapshot) => {
const documents = snapshot.docs //array of documents
documents.forEach((doc) => {
const docData = doc.data() //Data of that single document
console.log(docData)
renderToHtml() // Code that creates new HTML elements
})
})
This way you are creating new HTML elements for all the documents in your collection. The renderToHtml() function will contain that .innerHTML code.
Please make sure to see the logs in the console. They'll help understand the structure in a better way.

Address Firebase object by child value, and then modify that object?

I'm facing a little difficulty finding information about how to modify objects in Firebase Realtime Database. I'm adding items into my database in real-time, so I won't know ahead of time what the object key is. As you know, the database structure looks like this:
Say I want to address a child of "testing", whose category is "social", what I do is this:
firebase.database().ref("testing").orderByChild("category").equalTo("social")
But how exactly can I then address this child so as to update this entire child (including all the fields - "category", "date", etc.) or even delete it? Thanks so much for any help!
To update (or delete) a node in Firebase you must know the complete path to that node. If you don't know the complete path, you can use a query to determine the node(s) matching a certain condition.
So in your case you'll need to execute the query, loop over the results, and update each child node in turn. In code:
let query = firebase.database().ref("testing").orderByChild("category").equalTo("Social");
query.once("value").then((results) => {
results.forEach((snapshot) => {
snapshot.ref.update({ propertyToUpdate: "new value" });
});
});
If you want to delete the matching node(s), the innermost line would be: snapshot.ref.remove().

Firestore data modeling and angularFire

I have data model like this
Players-->root collection
Sports--->root collection
Players_Sports---root collection
I want get all the sports(Multiple sport) details or document player belongs.
For this I am using angularFireStore5
First, I am getting
Player details like this
this.db.collection('players').doc(id).get().toPromise()
Second, I am getting Player(user) linked PlayerSport
db.collection<any>('PlayerSports',ref => ref.where('playerId', '==', id) ).get().toPromise()
Third, I am trying to get Sports details based on ID'S,
db.collection<any>('sportsType', ref => ref.where('sportsType' 'in' [sportsIDs])).get().toPromise()
where SportIDs is arrary of ID that are linked in player_sports
First and Second steps works fine, but third steps is not giving any data or response
Could you please let me know where is the problem,
is it in Data model or code? my guess is that data model is not correct. Please guide me on this.
I would suggest getting the data from firebase and storing it inside a list so the app can access it later.
void getDataF(){
databaseReference
.collection("TableName")
.getDocuments()
.then((QuerySnapshot snapshot) {
snapshot.documents.forEach((f) {
iDFacList.add(f.documentID);
dbFacList.add(f.data["FieldName"]);
});
});
}
There is no sportsType field in the sportsType document as far as I can see.
If you're trying to find documents based on their SportsId field, you'll want ref.where('SportsId'....
Update
It seems that you're trying to find a document by its ID, which you can do with:
ref.doc(sportsIDs)
If you want to get multiple documents, or get a single document as a collection, you can use:
ref.where(firebase.firestore.FieldPath.documentId() 'in' [sportsIDs])

Categories