Executing various tasks during the mongodb update process: utilizing $addToSet, $inc, and performing aggregations such as $subtract

As I delve into learning how to use mongodb, I encountered a challenge when attempting to execute multiple operations in a single update query. Specifically, I encountered an error related to the $addToSet method.

Code:

function insertBook(db, title, author, price, edition, img, tags, pages, user, callback) {
    db.collection('books').update( 
        { $and:[{ "title":title }, { "edition":edition }] },    
        {
            "title": title,
            "author":author, 
            {$addToSet: { "img": { $each: img }}},  //error(1)
            {$addToSet: { "tags": { $each: tags }}}, //error(2)
            "edition": edition,
            "pages":pages,
            "price":price,  
            "shared":{ $subtract: ["$shared", 0] },
            $inc: {"copies": 1},            
            "availableCopies":{ $subtract: ["$copies","$shared"] },
            {$addToSet: { "ownedBy": user }}, //error(3)
            "registeredOn": { $type: "timestamp"}
        },
        { upsert: true }

    , function(err, result) {
        assert.equal(err, null);
        console.log("Inserted a document into the Books collection.");
        callback(result);
    });
};

MongoClient.connect(url, function(err, db) {
    assert.equal(err, null);
    var title = "Harry Potter and the chamber of secrets";
    var author = "J.K. Rowling";
    var price = 50.00;
    var img = "null";
    var tags = ["Fiction", "Magic"];
    var pages = 450;
    var user = "Amresh Venugopal";
    insertBook(db, title, author, price, edition, img, tags, pages, user, function(){
        db.close();
    });
});

Error:

/home/codewingx/repo/nodeapps/RESTful/model/bookPut.js:33
        {$addToSet: { "img": { $each: img }}},
        ^

SyntaxError: Unexpected token {

It appears that I may have overlooked something in my usage of the $addToSet method. The guide on https://docs.mongodb.org/manual/reference/operator/update/addToSet/#addtoset-modifiers only demonstrates the $addToSet operation, so what could be causing this particular error?

Answer №1

Your update statement includes a combination of updating entire documents, specific fields, and aggregate operations (such as $subtract). It's important to note that aggregation operators cannot be used in update statements. However, if you remove these aggregate operators, you can still create an effective update statement like the one shown below:

Additionally, you do not need to include $and as the default operation is 'and'.


  db.collection('books').update(
  { "title": title, "edition": edition },    
  {
    $set: {
           "title": title,
           "author": author,
           "edition": edition,
           "pages": pages,
           "price": price,
           "registeredOn": new Date()
          },
    $addToSet: { "img": { $each: img }, 
                "tags": { $each: tags }, 
                "ownedBy": user 
               },                       
    $inc: { "copies": 1 }
  },
  { upsert: true },
  function (err, res) {

  });

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

How to access the CSS and JS files in the vendor folder using linemanjs

Currently, I am in the process of developing a web application utilizing linemanjs. However, I have encountered an issue where the vendor css and js files are not being referenced correctly when explicitly included. I would appreciate any guidance on what ...

Translating from JavaScript to Objective-C using JSON

Can someone help me figure out how to correctly 'return' this JSON object in JavaScript? function getJSONData() { var points = '{\"points\": ['; var params = polyline.getLatLngs(); ...

Is there a bug hiding in the Angular code for the Codecademy Calendar App waiting to be found?

Currently, I am working on the Codecademy task - CalendarApp utilizing AngularJS which involves services and routing. Unfortunately, it seems to have some issues as the data is not displaying correctly and the expression: {{ day.date | date }} appears as i ...

Limiting Node.js entry with Express

I have a node.js script running on a server. I want to prevent it from being accessed directly from a browser and restrict access to only certain domains/IP addresses. Is this achievable? ...

Angularjs regex filter: applying regular expressions to filter data

I've created a regex pattern to match URLs like this: /^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$/ Now, I need to incorporate this regex into a filter that will specifically extra ...

Guide to importing an AngularJS controller into an Express file (routes.js)

Currently, I am in the process of developing a restful service and my goal is to organize my callbacks within controllers in order to avoid cluttering my routes.js file. Previously, I had been using controller = require(path.to.controller); This enabled ...

Modifying properties of an array of objects in React Native using JavaScript

I have a scenario where I am using Flatlist to render a couple of boxes. If the "shapes" element's "visible" key is false, the box will be blank. This visibility property is defined in state and I'm not sure if this is the correct approach. Now, ...

Generating a file using buffer information in node.js

From the front-end client side, I am sending a file to the server. On the server-side, the data received looks something like this: { name: 'CV-FILIPECOSTA.pdf', data: <Buffer 25 50 44 46 2d 31 2e 35 0d 25 e2 e3 cf d3 0d 0a 31 20 30 20 6f 6 ...

Creating multiple dynamic routes in Next.js based on specific IDs

Hey there! Currently tackling a challenge in my Nextjs project involving Events->Event->Schedule. My goal is to simply click on an event and be directed to the corresponding event details. Within the event, there should be a schedule that links to th ...

Are there any potential performance implications to passing an anonymous function as a prop?

Is it true that both anonymous functions and normal functions are recreated on every render? Since components are functions, is it necessary to recreate all functions every time they are called? And does using a normal function offer any performance improv ...

Encountering an isObject issue while using the @material/core package

When attempting to run the project, I encountered this error in the console: isobject error Upon inspecting the package-lock.json file, I discovered that the isobject dependency was missing in @material-ui/core. Adding it manually resolved the issue. pac ...

Ways to specifically load a script for Firefox browsers

How can I load a script file specifically for FireFox? For example: <script src="js/script.js"></script> <script src="js/scriptFF.js"></script> - is this only for Firefox?? UPDATE This is how I did it: <script> if($. ...

Mastering Vuex: effectively managing intricate data structures and dynamic state transformations

Let's say I'm utilizing an external API that interacts with Machine objects. With the API, you can create a Machine using createMachine, resulting in a complex object with various nested properties and functions to modify its state. The API inclu ...

Refreshing the entire page upon modifying a single state

I am currently in the process of constructing a page that includes numerous Charts, and I am utilizing a Material UI menu to switch between graphs. Each time I click on a new MenuItem, it alters my state and presents a new array of components. The pr ...

Causes of the error message 'TypeError: res.render is not a function'

I have set up an express application with the following code: var express = require('express'); var router = express.Router(); var passport = require('passport'); var User = require('../models/user'); var request = require(&a ...

Attempted to create registrations for two views using the identical name RCTScrollView

Having trouble running my React Native app on iOS, I keep getting an error while the Android version works perfectly fine. Does anyone have any insight on this issue? XCode 11.5, RN 0.61.5, Using React Native CLI I've searched multiple sites but hav ...

Issues with XFBML Like Buttons failing to load when generating numerous posts dynamically on a single page

On my webpage containing multiple posts, I am attempting to insert a Facebook LIKE button for each post. Utilizing XFBML code, I am trying to populate like buttons under every individual post with a unique URL, corresponding to the post URL. Here is the c ...

After deploying to Firebase, animations suddenly cease to function

After running npm run-script build and deploying my React app to Firebase hosting with firebase deploy, I encountered an issue where my animations stopped working. I'm puzzled as to why this is happening, especially since I've included keyframes ...

Mongo does not support restoring user passwords

Here is the situation I am facing: Perform a Mongo database dump (using the command mongodump) Change the password of one of the admin users Restore the Mongo database (using the command mongorestore) UPDATE: When doing the database dump, I executed th ...

Correcting W3C validation issues is essential

I am encountering errors in my W3C validation process. Even though I have set <!DOCTYPE HTML> for my page, I continue to experience issues as shown in the image below. I have been trying to troubleshoot and resolve these errors without much success ...