How can MongoDB insert a field that corresponds to a JavaScript variable?

I'm having trouble adding a new field to MongoDB. The database accepts my Javascript variable as data, but not as the name for the new field:

function appendInformation(question, answer) {
    Sessions.update({ _id: Id }, { question : answer });
}

The correct answer is inserted, but it appears in the document as question: {answer} instead of {question} : {answer}

Answer №1

To update the Session document with a new field, you should utilize the $set method.

function addData(q, a) {
    var info = { };
    info[q] = a;
    Sessions.update({ _id: Id }, { $set : info });
}

For more information on how to use $set, refer to the documentation.

> db.so.remove()
> var info={"question 1" : "the answer is 1"};
> db.so.insert(info);
> db.so.find()
{ "_id" : ObjectId("520136af3c5438af60de6398"),
               "question 1" : "the answer is 1" }
> var info2={"question 2" : "the answer is 2"};
> db.so.update({ "_id" : ObjectId("520136af3c5438af60de6398")}, { $set : info2 })
> db.so.find()
{ "_id" : ObjectId("520136af3c5438af60de6398"), 
               "question 1" : "the answer is 1",
               "question 2" : "the answer is 2" }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for preventing page breaks (when printing or saving as a PDF) in lengthy HTML tables

Here is the link to a single HTML file (including style and scripts): FQ.html The problem I'm facing can be seen in this image: https://i.sstatic.net/Nr4BZ.png I've tried several solutions, the latest of which involves the following CSS... @me ...

Using a global variable in Vue and noticing that it does not update computed variables?

Currently, I'm in the process of developing a web application and have begun implementing authentication using firebase. Successfully setting up the login interface, my next step is to propagate this data throughout the entire app. Not utilizing Vuex ...

Occasionally encounter errors while fetching data with the Twitter API

Occasionally, I encounter a problem with the code below. Sometimes it works fine, but other times it throws error 420 with a vague JSON parse error message. Any suggestions on what might be causing this issue? The error message is as follows: Error gett ...

Obtaining Mouse Click X, Y, and Z Coordinates with Three.js

I am currently utilizing version 68 of three.js. My objective is to gather the X, Y, and Z coordinates upon clicking somewhere on the canvas. Despite following the steps outlined in this guide, I am encountering a consistent Z value of 0: Mouse / Canvas X ...

Trouble selecting options in hierarchical data

I've been attempting to run this sample code for selecting an option from a select element with hierarchical data, but it seems to be having some issues. $scope.options = [ { id: 1, info: { label: "Item 1" } }, { id: 2, info: { label: ...

A function that retrieves the empty values from an array and returns undefined if there

After undergoing a time-consuming process, the sample below shows that the array values are returned empty. function myFunction() { let myArray = []; let pastArray = [1, 2, 6, 7, 8, 1, 9, 6, 0] pastArray.forEach(item =>{ setTimeout(function(){ myA ...

Adjust object values dynamically with TypeScript by identifying the corresponding keys

Currently, I am in the process of creating a function in TypeScript that will return another function allowing me to modify the keys of an object. This specific function is intended for use within a React reducer. For instance, if I have a state object wi ...

What is the best way to transfer information between pages using onclick in node.js and express?

script1.js const database = new Datastore('database.db'); database.loadDatabase(); app.get('/api', (request, response) => { database.find({},(err,data)=> { if(err){ response.end(); return; ...

Issue with Mobile NavBar remaining visible after clicking on target element in HTML CSS

On my website, everything works perfectly with the Nav bar except for when I am on mobile. When I click on any href from my Nav Bar, it directs me to the correct location but does not close the Nav Bar afterward. I need it to function this way: After click ...

jQuery auto-complete feature that cannot be edited

We are experimenting with implementing a non-editable jQuery auto-complete feature. For example, when a user selects a value from the auto-complete dropdown, they should not be able to modify it. However, if they press the backspace key, the old value shou ...

What is the process of linking this JavaScript code to an outer stylesheet and integrating it with the HTML document?

After encrypting an email address using Hiveware Enkoder, the result can be found below. obfuscated code I typically include it directly inside the div as is. However, I would like to streamline my code by placing it in an external file. While I know ho ...

iOS devices are experiencing issues with touchstart and touchend events not functioning when utilizing jquery mobile and cordova

During a previous project, I encountered no problems with the following code snippet. It effectively utilized touchstart and touchend events to adjust the CSS of a button: <script> $('input[type="button"]').on('touchstart', func ...

Angular JS is experiencing issues with two modules not functioning properly on a single page

Angular JS is a new technology for me. I have two modules, first2a and first22. Each module contains a controller named model1 and model2. Here is the HTML code: <!DOCTYPE html> <html > <head> <link rel="icon" ...

Angular 2 isn't triggering the custom validator for every keypress

I have implemented a custom validator for Reactive forms in Angular 2. However, I am facing an issue where my function is only validating the first key press in the text field. Ideally, the custom function should validate each key press. Can someone please ...

Switch button while moving cursor

I'm struggling with getting this 2048x512 image, which has 4 stages of transition, to work properly. https://i.sstatic.net/1PBvX.png While I know how to switch it to the final stage on hover, I can't seem to figure out how to incorporate a trans ...

Looking to clear a textfield when focused if it contains zero, and when unfocused if it is empty, then automatically insert zero?

What is the best way to clear a text field when it contains zero on focus, and set it back to zero if it's empty on focus out? How can this be implemented globally for every text field by adding a common class to all text fields? ...

Choosing a versatile model field in a Django CMS plugin

Currently, I am developing a Django CMS plugin that includes a model choice field dependent on another field in the form. To update the choices in the model choice field based on the trigger field selection, I am using AJAX. However, when submitting the fo ...

Struggling with Getting My Animation to Function Correctly

I am trying to create a JQuery Animation that will move a div covering a text box up into the border when clicked. Despite multiple attempts, I can't seem to get the animation to work properly. Any suggestions? JavaScript function moveup(title,text ...

Passing a property to a click event handler in ES6 with React: What's the best approach?

Struggling with passing props to a click function in my React learning journey. I'm attempting to make a basic ES6 counter component that increases when a button is clicked. The click function I have so far is: click() { this.setState({ c ...

Is it possible to create a polar grid using Three JS Gridhelper?

While working with Three JS, I was able to add a grid to the scene using the GridHelper. Is there a similar function that can produce a polar grid? This is how the geometry for a 2D Cartesian plane is created (source): var geometry = new THREE.Geometry() ...