I want to update all the fields in a MongoDB document and I have a Javascript object that contains all these fields. I could easily type out each field to update but this seems like a lot of manual work and not reusable. I wanted to do something like below but this creates an object containing all the new field data within the document called newData.
I've tried JSON.stringify on the variable but the format isn't appropriate for update.
var newData = {
_id:ObjectId("53245234..."),
id: 88888,
firstData: "someData",
secondData: 787855,
thirdData: [ 45,17,12,234]
};
var collection = db.get('CollectionToUpdate');
//strip out dB id so as not to overwrite it, possibly not needed
if ("_id" in newData) {
delete newData["_id"];
}
//find the correct document based on program generated id and update
collection.update({id: newData.id}, {
newData
})
If you trust newData will not have any keys you don't intend (like update operators) this should work:
var collection = db.get('CollectionToUpdate');
collection.update({id: newData.id}, newData)
Note that this replaces the document. I assume that is what you meant by "update all the fields". update does not replace "_id".
Documentation for update
Related
Don't know how to go about adding new fields into a map in Firestore using a variable rather then a hardcoded field name.
I have a data structure in firestorm. The collection is called webQuiz and the document is called '12345. The data structure looks like:
roomName: Demo0
roomNumber: 46532
people:{11111:"David, 22222:"Peter}
Note that people is a map data object.
I would like to add another field to the people map. The code below works but instead of the data looking like
people:{11111:"David, 22222:"Peter, 44444:"Cathy"} it looks like
people:{11111:"David, 22222:"Peter, x:"Cathy"}
How can I use a variable which holds the field name in this situation? The x should be a variable but it is picked up literally as a property.
function testing(){
var x = "44444"
var y = "Cathy"
var cityRef = db.collection('webQuiz').doc('12345');
var setWithMerge = cityRef.set({
people: {x: y}
}, { merge: true });
I expect the output in firestorm to be
people:{11111:"David, 22222:"Peter, 44444:"Cathy"} but the actual output at the moment is
people:{11111:"David, 22222:"Peter, x:"Cathy"}
Thanks
You'll need to use the full field path as the key of the update:
var setWithMerge = cityRef.set({
`people.${x}`: y
});
This will prevent re-writing the entire "people" field, since you are specifying which property of the map to change directly.
Note that the field name and the property name are separated by a period.
During storing an object to my firebase, I am expecting the structure as image below, but what I get was a generated running number as a key. This is my code to store an object to firebase
var location = [];
location.push({
ms_jhr_1 : {
name: value
},
...
});
const a = firebase.database().ref('Food/'+id);
a.set(location);
How do I keep my structure without generate the running number?
The problem is you are using an array to store your data and then setting that array in firebase. To get the expected result you have to modify your code a little bit.
Here use this and remove other code
const a = firebase.database().ref('Food/'+id);
a.set(ms_jhr_1);
So you just need to pass the object you want to store under that id and not the whole array.
Note:- If you want to store multiple entries under one id then you have to push all those entries in an Object and not in array.
So it will look something like this
var location = {};
Now use for loop to insert all your data into this object (Remember, you are adding objects inside an object). You don't need array. Because in firebase data is stored in JSON tree format.
Hope it helps.
I have a form with a lot of inputs and values. I want to push all the data to a firebase database. I could assign variables to each field value as:
let name = $("#field1").val();
let surname = $("#field2").val();
etc etc, but this feels very inefficient.
I want to create a object and loop through all input fields and map their name and value, something like this:
const collection = {};
$('form input').each(function () {
collection[$(this).attr('name')] = $(this).val();
});
Then I want to push all the data to firebase. But how do I push the entire object to firebase?
That's as simple as:
firebase.database().ref().push(collection);
Of if you want it under a specific location/path in the database:
firebase.database().ref("specific/place").push(collection);
Btw: I highly recommend reading the Firebase documentation on reading/writing lists of data.
The internet is full of resources for dealing with arrays, but often objects are a more natural fit for data and seemingly more efficient.
I want to store key-value objects under dynamic field names like this:
project['en-US'] = { 'nav-back': 'Go back', ... }
project['pt-BR'] = { 'nav-back': 'Volte', ... }
Doing this seems like it would be more efficient than keeping an array of all languages and having to filter it to get all language entries for a given language.
My question is: How can I insert a key-value pair into an object with a dynamic name using mongoose? And would the object need to exist or can I create it if it doesn't in one operation?
I tried this:
await Project.update(
{ _id: projectId },
{
$set: {
[`${language}.${key}`]: value,
},
});
But no luck regardless of if I have an empty object there to begin with or not: { ok: 0, n: 0, nModified: 0 }.
Bonus: Should I index these objects and how? (I will want to update single items)
Thanks!
In mongoose, the schema is everything. It describe the data you gonna read/store from the database. If you wanna add dynamically a new key in the schema it's gonna be hard.
In this particulary case I would recommend to use the mongodb-native-driver which is way more permissive about the data manipulation. So you could read the data in a specific format and dynamically add your field into it.
To resume my thought, how should your dynamic change happen :
Use mongodb-native-driver to insert the new key into the database data
Modify the mongoose schema you have in the code (push a new key into it)
Use mongoose to manipulate the data afterward
Do not forget to dynamically update your mongoose model or you won't read the new key at the next find.
I solved this using the original code snippet unchanged, but adding { strict: false } to the schema:
const projectSchema = new Schema({ ...schema... }, { strict: false });
At the moment, Firebase doesn't stores the data in the order it is entered. For ex - There could be 2 existing childs and a new child is inserted, that new child goes and sits in the middle of the already existing ones! I guess this works by alphabet order but I want to store data in the correct order only.
firebase.database().ref('someChildRef').set({
//Could insert anywhere
});
I think push could insert it in the correct order but push also generates a unique key which I don't want, I want to insert data only using set and in the correct order.
It is not possible to insert data into Firebase into a desired position. Firebase data is sorted alphabetically and all newly inserted data will be rearranged accordingly.
Use query rules to return the data in the order you want.
Such as:
orderByChild()
orderByKey()
orderByValue()
equalTo()
You are correct about push(), it will always create a unique key and add to the end, just as pushing to an array will add to the end.
It sounds like you're looking for Firebase's push() method, which generates a unique key based on the timestamp:
firebase.database().ref('someChildRef').set({
//Will result at "the end"
});
var messageListRef = new Firebase('https://samplechat.firebaseio-demo.com/message_list');
var newMessageRef = messageListRef.push();
newMessageRef.set({ 'user_id': 'fred', 'text': 'Yabba Dabba Doo!' });
// We've appended a new message to the message_list location.
var path = newMessageRef.toString();
Try using the push() method instead of set. According to their docs:
The unique name generated by push() is prefixed with a client-generated timestamp so that the resulting list will be chronologically-sorted.
Reference: https://www.firebase.com/docs/web/api/firebase/push.html