Exploring the capabilities of mongojs: Adding items to arrays within fields

I've been researching extensively on this subject, but I'm completely stumped. Here's my dilemma (I'm working with node.js and mongojs):

I want to create documents like the following:

{ 
    "_id" : ObjectId("50ce2f7f98fa09b20d000001"), 
    "beginTime" : 1355689855016, 
    "tags" : {
        "primary": [ 29, 12, 16], 
        "secondary": [6, 8, 9]
    },
    "user" : "50bdddc601de4681d666835f"
}

However, when I attempt to add new tags under "primary" using variables like so:

tags = {};
tags[request.body.relevance] = request.body.tag;
return db.activities.update({
  '_id': db.ObjectId(request.body.activity),
  'user': request.session.user.id
}, {
  $push: {
    tags: tags
  }
});

I end up with:

{ "_id" : ObjectId("50ce2f7f98fa09b20d000001"), "beginTime" : 1355689855016, "tags" : [ { "primary" : 29 }, { "primary" : "24" }, { "primary" : "1" } ], "user" : "50bdddc601de4681d666835f" }

I've tried numerous different approaches, even attempted nesting $push (which turned it into a field). Nothing seems to work. At this point, I'm feeling extremely frustrated.

If you have any insights or solutions, please lend me a hand. Much appreciated.

Answer №1

When using the $push operator, make sure that the value specified is for the array field you want to add to, and not the parent field.

Consider the following approach:

...
return db.activities.update({
  '_id': db.ObjectId(request.body.activity),
  'user': request.session.user.id
}, {
  $push: {
    'tags.primary': tags.primary,
    'tags.secondary': tags.secondary
  }
});

UPDATE

If you need to handle this dynamically, use a method like the one below:

...
var push = {};
push['tags.' + request.body.relevance] = request.body.tag;
return db.activities.update({
  '_id': db.ObjectId(request.body.activity),
  'user': request.session.user.id
}, {
  $push: push
});

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

It seems like the method has already been executed despite encountering an unexpected end of JSON input error

Currently, I am utilizing the etherscan API to retrieve logs for certain events. Although my JSON parsing method seems quite traditional, an error is being thrown stating "unexpected end of JSON". function getEventHistory() { const topic0 = web3.util ...

"VS Code's word wrap feature is beneficial for wrapping long lines of text and code, preventing them from breaking and ensuring they are

text not aligning properly and causing unnecessary line breaks insert image here I attempted to toggle the word wrap feature, installed the Rewrap plugin, and played around with vscode settings ...

Does using the useState() hook in React automatically empty out the input fields?

Every time I update a state in my React application, it mysteriously erases the content of my inputs like checkboxes and numbers. Let me share a simple example to demonstrate this issue. import React, { useState } from "react"; export default fun ...

What is the best way to minify and concatenate multiple CSS files only after converting SCSS to CSS with Gulp?

When attempting to convert my scss files to css files using gulp, I encountered an issue. After writing the scss code, it is easily converted to css. However, I wanted to minify this css and save it in a different folder called 'min'. Within the ...

Require.js and R.js optimizer overlooks shimming configuration

I am facing an issue where R.js is not loading my shim properly, causing jQuery to load before tinyMCE which results in tiny being initialized before it has fully loaded. How can I resolve this problem? build-js.js: var requirejs = require('requirej ...

Getting a jquery lightbox up and running

After experimenting with three different jquery plugins in an attempt to create a lightbox that appears when clicking on a link containing an image, I am currently testing out this one: . Despite adding the plugin source in the head and ensuring that the l ...

Are there any libraries available that can assist with managing forms similar to how Google Contacts handles them

By default, Google Contacts has a feature where the form displays values with some of them being read only. However, when you click on a value, it converts the field into an editable form so you can easily make changes. After editing and pressing enter, th ...

Difficulty in detecting state changes without refreshing the component when using Redux and React

I'm encountering difficulties detecting state changes from my Redux reducer in a React application. When I modify the state within one component, the other component in the app does not get the update unless the component is reloaded or refreshed. Let ...

The PHP script is not being activated by AJAX

I am completely baffled by the situation at hand. Sometimes, I open a different browser to test my changes and it works as expected. But then, when I try again, it fails. It's driving me crazy. On syllableapp.com, I set up a MySQL database that I can ...

What steps should I take to address the error message "TypeError: express-validator is not a function

I am currently utilizing express-validator version 6.4.0 and encountering an error when running the server. I have attempted to implement custom validation by organizing separate files for validator, controller, and routes. Here is the primary server file ...

The function res.sendFile() does not display files on the browser

For the past few days, I've been facing a challenge. Does anyone have any suggestions? When I click on a login button, I authenticate the user, generate a token, store it in cookies, and then use it in the headers of a request to display the homepage. ...

Receiving HTTP POST data using Classic ASP script

I'm currently working on a project and have come across an area where I am facing some challenges. Despite my best efforts, I haven't been able to find a solution using Google. In my ASP web application, I've added an HTML canvas that I nee ...

Spin the object around the z-axis, with the point serving as the center of rotation

I have a unique challenge with positioning a HUD object on the front of a tube in Three.js. The HUD needs to align itself based on a vector point, always facing towards the high side of that point, regardless of the direction and position of the tube. To b ...

I am experimenting with an express middleware that can either return next() or next("route")

After developing a middleware function that returns next() if a route's parameters are defined by queryItems, I came across a useful tool called node-mocks-http. However, it does not fake the next object. This led me to explore how this can be achieve ...

Is it possible to create a website with a single session for all users using JavaScript

Greetings everyone, I am excited to be posting for the first time on stackoverflow. After dedicating a week to learning javascript and achieving some things I am proud of, I have hit a roadblock. As a self-learner, I kindly ask for your understanding. Cur ...

Trouble arising from PHP's encoded array

I am encountering an issue with retrieving a value from PHP and passing it to Javascript. The PHP array is encoded like this : echo json_encode($myArray); On the Javascript side, I use the following code within the $.ajax method: success:function (data) ...

Steps for transitioning a VUE JS project to TypeScript

Is it possible to transition a VUE JS project from JavaScript to TypeScript without rewriting everything? I heard from a friend that it can be done through the VUE CLI, but I haven't been able to find any documentation or articles on this method. Has ...

Align the content to the right and center it within the table

One common issue I face is working with tables that contain numbers requiring right alignment to ensure the ones/tens/hundreds/thousands places line up correctly. Here's an example: 2,343 1,000,000 43 43,394 232,111 In these tables, ...

Exploring the world of Node.JS and AngularJS through the integration of API routes

Currently, my backend is built using Node.JS with Express and serving as my API servlet. On the frontend, I'm utilizing AngularJS for the user interface. After numerous searches on Google, I was able to resolve an issue where I faced challenges using ...

Discord.JS Guild Member Cache Responses that are not recognized as valid

My automated messaging bot has been running smoothly for the past 6-8 months, but recently it encountered a strange issue with a specific user. Upon checking the cache of the Discord server it operates on, I noticed that it only returned two members - myse ...