Update many in mongoose [duplicate] - javascript

This question already has answers here:
MongoDB: update every document on one field
(4 answers)
Closed 3 years ago.
I have a very simple case. I want to update my collection every midnight.
Im using node-schedule:
schedule.scheduleJob('0 0 * * *', () => {
Users.updateMany();
});
All I want to do, is to loop over every document in my collection (Users) and then if User.created is false, I want to turn it into true.
In javascript it would be:
for (let user in Users) {
if (user.created === false) {
user.created = true;
}
}
How to do it in mongoose? Thanks!
Edit: The story is very simple, I just want to iterate over every element in my db using mongoose and if iterated element has field "created" === false, change it to true.

You can use updateMany() methods of mongodb to update multiple document
Simple query is like this
db.collection.updateMany(filter, update, options)
For more doc of uppdateMany read here
As per your requirement the update code will be like this:
User.updateMany({"created": false}, {"$set":{"created": true}});
here you need to use $set because you just want to change created from true to false. For ref. If you want to change entire doc then you don't need to use $set

You first need a query to find the documents you want to update. This is simply:
{"created": false}
Then you need an update query to tell mongo how to update those documents:
{"$set":{"created": true}}
You need to use the $set operator to specify which fields to change, otherwise it will overwrite the entire document. Finally you can combine these components into a single mongo call with an additional parameter to tell mongo we want to modify multiple documents:
User.update({"created": false}, {"$set":{"created": true}}, {"multi": true}, (err, writeResult) => {});
Mongoose tries to closely replicate the mongo API so all this information can be found solely within MongoDB's documentation: https://docs.mongodb.com/manual/reference/method/db.collection.update/

Related

Firestore Array of map not updating

So I'm working on a personal project to learn react-native and Firestore.
I have a DB like this:
And I want my code to add a new battery in the array batteries.
The elements in the array are just a map{string, string}
The problem is that when I update the array with a new brand that's work but if I want to update it with the same brand again have,
so having by the end
batteries[0]: {'brand': 'cestmoi'}
batteries[1]: {'brand': 'cestmoi'}
The DB doesn't update, doesn't have any error or so.
I don't understand why and I followed their tutorial. Here is my code:
async function addData(collection, doc, value) {
console.log(`Add data ${value.brand}`)
try {
const result = await firestore()
.collection(collection)
.doc(doc)
.set({
batteries: firestore.FieldValue.arrayUnion(value)
})
console.log(result);
return result;
} catch (error) {
return error;
}
}
I use try-catch by habit but I don't know if the then...catch is better or not.
As already #windowsill mentioned in his answer, there is no way you can add duplicate elements in an array using client-side code. If your application requires that, then you have to read the entire array, add the duplicates and then write the document back to Firestore.
However, if you want to update an existing element in an array of objects (maps) then you have to use arrayUnion with the entire object. If you want to understand the mechanism better, you can read the following article which is called:
How to update an array of objects in Firestore?
arrayUnion says that it "adds elements to an array but only elements not already present". Maybe it does a stringify or something to check equality and therefore doesn't add the new element. I think you'll have to 1. get the current list, 2. add your element, 3. set the batteries field to the updated list.

Firebase retrieve a document based on grandchild's value which is a collection [duplicate]

This question already has an answer here:
Firebase query if child of child contains a value
(1 answer)
Closed 1 year ago.
Is there a way to Query a collection which is a grandchild in firebase?
Current firebase structure:
{
products: {
"dfwojozijowjfoije": {
"barcodes": ["12345", "5678"],
"productName": "someProduct"
},
"sdafsdasdfasdfadsf": {
"barcodes": ["99999", "88888"],
"productName": "someProduct2"
}
}
}
Current Query that I use:
await firebase
.database()
.ref('products')
.orderByChild('barcodes')
.equalTo('88888')
.on('value', snapshot => {
setProductName(snapshot.val())
}
)
There is no way in a Firebase Realtime Database query to check for the existence of a value in an array. If you're trying to do this, it typically means that your data structure is actually not an array, but a set.
Since a set data type doesn't exist, you can't store it in Firebase natively though. The closest equivalent is not an array though, but a map like this:
"barcodes": {
"12345": true,
"5678": true
}
This may look a bit weird at first, but it has the exact properties that you're typically looking for in a set: the values (that are now keys) are by definition unique in the parent node, and you can test for the presence of a specific value/key.
Unfortunately, you still won't be able to query on this structure, as you can only define indexes on keys that you know, and I'm assuming that the barcodes are a rather infinite set of values.
So instead you'll have to define an inverted data structure, as I've explained here: Firebase query if child of child contains a value

Append to an arary field in Firestore

I'm using Firebase and Vuejs to create an database element, which has object array inside.
That's how the field looks, and I want to add tasks through the form into the 'moreTasks' as an array.
I tried using this, but it just creates new entity in the database.
db.collection('Tasks').add({
tasker: this.tasker.taskerName
})
I also tried checking API but I couldnt understand the refs, because I was using different methods to achieve that goal.
creatTask() {
db.collection('Tasks').add({
task_id: this.task_id,
name: this.name,
What would be correct way to approach this problem?
You can append an item to an array using FieldValue.arrayUnion() as described in the documentation. For example:
// Atomically add a new region to the "regions" array field.
washingtonRef.update({
regions: firebase.firestore.FieldValue.arrayUnion("greater_virginia")
});
The accepted answer used to be correct but is now wrong. Now there is an atomic append operation using the arrayUnion method:
https://firebase.google.com/docs/firestore/manage-data/add-data#update_elements_in_an_array
This is true as long as you are using firestore and not real time db (which I assume is the case from the tags)

Backbone findWhere finds nothing [duplicate]

This question already has answers here:
How do I get a model from a Backbone.js collection by its id?
(2 answers)
Closed 6 years ago.
My collection has 4494 models. I try to use findWhere to get specific model by id. The findWhere returns 'undefined'.
It works ok if I limit the number of models. The strangeness heppens when the number of models is over 100.
var users = this.usersCollection;
console.log(users);
console.log(users.findWhere({uid: 1}));
While the problem is solved (using findWhere before the collection is actually fetched) thanks to TJ's comment, you might want to use .get instead of findWhere when searching a model by id.
If your User model looks something like this:
var User = Backbone.Model.extend({
idAttribute: 'uid',
// ...
});
You could get a user by id from the collection directly:
var user = users.get(1);
You can also use get with the model's cid or the model instance.
user === users.get(user.cid)
user === users.get(user)
This is better because Backbone keeps a hash of the models with the specified id attribute as the key in addition of the usual array.
The problem was that I tried to use my collection before it was completely fetched.

Add element to array collections.update in meteor

Polls.update({_id: id}, {$set : {already_voted[length]: ip});
Now this obviously doesn't work. I can't simply put a variable "length" in there.
Basically I have already_voted which is an array and I want to add a new ip to this array. The way I handle this currently is by getting the old length and using the old length as the new index to add the element.
I am wondering how I should go about doing this as my current setup does not work.
To clarify : I don't have the whole array, I just want to add a new element into the array in the Poll document.
Use the $push Mongo operator:
Polls.update({ _id: id },{ $push: { already_voted: ip }})
See the docs here.
It is quite easy to add element to array in collection in meteor:
collection.update({_id: "unique id"},{$push:{already_voted: ip}});
You can even user upsert instead of update as per you requirement.
something like this:
collection.upsert({_id: "unique id"},{$push:{already_voted: ip}});

Categories

Resources