How to remove all items of a Mongo collection - javascript

I have seen that to remove all items of a Mongo collection using JavaScript I should use :
DockerStats.remove(); //where DockerStats is my collection
So my goal is to purge the DB every 20sec so I did the following code :
setInterval(Meteor.bindEnvironment(function(){
DockerStats.remove();
console.log("ok")
}),20000);
But when I start the app I had +/- 1000items then despite the terminal wrote 2 times "ok" I still have more than 1000items so it doesn't work because even if I check right after the "ok" I have more than 1000items and the number is always growing up.
So maybe I'm removing the items with the wrong way ?

According to the docs, you need to pass in an empty object to delete the whole collection. So, the below would remove all students from the Students collection:
Students.remove({})
I think this is because if you want to remove everything and start over you would use the drop method and recreate it, which the docs says is more performant.

Related

How to load data onScroll in ReactNative with Firebase Realtime Database

i want to load data from my realtime database, but only 15 entries everytime, because the database is huge. The database has a name of the vocable and got information about it like translations and stats. I want to sort it alphabetic by the value "wordENG", but there is a problem, when i use orderByChild like this:
database()
.ref(`vocables/${UID}`)
.orderByChild("wordENG")
.startAt(requestCount)
.limitToFirst(15)
.once("value")
.then(snap => {
console.log(snap.val());
})
When i try to use startAt, to get the data on scrolling, i get the problem that startAt need to be a string, so a word of the database list. I don't want to store this word everytime and search for new one after that, but currently i cannot see another way. Is there a way to get data alphabetic on scrolling with a number to count or do i need to realize it with saving the last word and search from there?
Pagination with Firebase queries work based on knowing the anchor item, not on offsets. So you will need to indeed know the wordENG value of the node to start at (or start after with the relatively new startAfter method), and possibly the key (if there may be multiple child nodes with the same wordENG value.
If you're new to Firebase, I recommend also reading some of the previous questions about pagination, as this comes up regularly.

Meteor MongoDB Filter Parent Records by Child Fields

How would I go about filtering a set of records based on their child records.
Let's say I have a collection Item that has a field to another collection Bag called bagId. I'd like to find all Items where a field on Bags matches some clause.
I.e. db.Items.find( { "where bag.type:'Paper' " }) . How would I go about doing this in MongoDB. I understand I'd have to join on Bags and then link where Item.bagId == Bag._id
I used Studio3T to convert a SQL GROUP BY to a Mongo aggregate. I'm just wondering if there's any defacto way to do this.
Should I perform a data migration to simply include Bag.type on every Item document (don't want to get into the habit of continuously making schema changes everytime I want to sort/filter Items by Bag fields).
Use something like https://github.com/meteorhacks/meteor-aggregate (No luck with that syntax yet)
Grapher https://github.com/cult-of-coders/grapher I played around with this briefly and while it's cool I'm not sure if it'll actually solve my problem. I can use it to add Bag.type to every Item returned, but I don't see how that could help me filter every item by Bag.type.
Is this just one of the tradeoffs of using a NoSQL dbms? What option above is recommended or are there any other ideas?
Thanks
You could use the $in functionality of MongoDB. It would look something like this:
const bagsIds = Bags.find({type: 'paper'}, {fields: {"_id": 1}}).map(function(bag) { return bag._id; });
const items = Items.find( { bagId: { $in: bagsIds } } ).fetch();
It would take some testing if the reactivity of this solution is still how you expect it to work and if this would still be suitable for larger collections instead of going for your first solution and performing the migration.

Firestore says I have inequality filter on multiple properties, when I don't

I am trying to do a "small hack" to avoid reading the User document everytime the page loads. So I save it locally, everytime the page loads I get the local version, get the updated_at property and then do something like WHERE last_updated > {{updated_at}}. For that, I want to use this:
firebase.firestore().collection('User')
.where(firebase.firestore.FieldPath.documentId(), '==', firebase.auth().currentUser.uid)
.where('updated_at', '>', updated_at)
.get()
As you can see, I have one equality (==) and one inequality (>). Why do I get the following error on the console:
FirebaseError: Cannot have inequality filters on multiple properties: updated_at
at new t (https://www.gstatic.com/firebasejs/6.0.2/firebase-firestore.js:1:47054)
at t.fromRpcStatus (https://www.gstatic.com/firebasejs/6.0.2/firebase-firestore.js:1:116660)
at t.fromWatchChange (https://www.gstatic.com/firebasejs/6.0.2/firebase-firestore.js:1:125914)
at t.onMessage (https://www.gstatic.com/firebasejs/6.0.2/firebase-firestore.js:1:242411)
at https://www.gstatic.com/firebasejs/6.0.2/firebase-firestore.js:1:241212
at https://www.gstatic.com/firebasejs/6.0.2/firebase-firestore.js:1:241997
at https://www.gstatic.com/firebasejs/6.0.2/firebase-firestore.js:1:144869
I am doing this to try to avoid reading from the database if the local version is the same as the one in the database. Maybe if you have a better way, please let me know.
Thanks
firebaser here
The equality check you have on documentId() is internally converted into a range check by Firestore, because the keys are stored as the last items in existing indexes (if I understand correctly). And that means that server-side you're trying to perform two inequality/range checks, which isn't allowed.
So the behavior you are seeing is correct. But it's definitely not intuitive, and the error message is also not helpful. We'll look for a way to improve the error message by detecting this combination.
I had the same problem and I implemented the following hack: I added the id as part of the field name on which I made the check for the latest version. If your logic allows you to do that, for you this would mean:
firebase.firestore().collection('User')
.where(id + '_updated_at', '>', updated_at)
.get()
This allows to bundle in just one where statement both the check on the id and on the date (documents with different ids wont have the field id + '_updated_at' and wont therefore be selected).
Worked like a charm for me

Mongo add document in the middle of collection

When I insertOne() document in the collection Mongo add the document between the first and last document.
It is expected to be added at the end, right? But for me ideally would be to add the document at the beginning, for example as .unshift() JS works.
I'm building Blog so new posts should be added at the top of the list.
But I can always .reverse() of course .
Main problem is why document is added in the middle.
You should sort the collection by creation time(when you are trying to output them sorted by creation time) rather than trying to change to order of insertions in the collections.
db.posts.find().sort({creation_time: -1})
This way the recent entries will come out on top.
Ref: https://docs.mongodb.com/manual/reference/method/cursor.sort/#cursor.sort

Can't delete items from Mongo Database in Meteorjs

I have created an object in Meteorjs to hold the database info for N numbers of dice rolls, and then the dice are displayed using handlebars #each iterator. Here is some of my code:
The global Mongo collection:
Items = new Meteor.Collection('items');</code>
When I roll the dice, this is what happens to the collection when a button is clicked:
//Don't want to bore you with all code, so here's just important parts...
var randomNumber=Math.floor(Math.random() * numSides) +1);
var numDice = 6;// It's really a variable passed in, but for here it's 6.
for (var i = 0; i < numDice; i++) {
Items.insert(item: randomNumber)
};
And then they display the info as dice because it displays numbers that I have CSS'd to look like Dice. But I'm straying here... Anyway, the dice rolling is awesome, but I want to clear the dice when I roll again. right now, they just keep adding up. And when I try to use any method to delete Mongo DB Items stuff, it crashes my app. Since I'm not sure how to debug very well yet in a browser, I need some help, and I'mm going to ask it here...
Now, my main problem is, when the dice are rolled again, I want to purge the database and start again. I am new to JavaScript and Meteor, and come from Java && Ruby land, so any suggestions are greatly appreciated.
I've tried
Items.removeIndexes(),
Items.purge(),
Items.remove({})
They all just freeze my app, and the numbers I displayed in the #each iterator are still there. I thought it would delete the stuff, and push the changes... No??? Please help.
The code is on GitHub # http://www.github.com/rabbitfighter81/DMware/
You should use the remove method, but if you call it from the client, you can only remove one document per call, and the selector must refer to the documents _id field. So, here's an example to remove all the documents in a collection the client has:
TheCollection.find().forEach(function(doc){
TheCollection.remove(doc._id)
})

Categories

Resources