Enable the upsert option in MongoDB Mongoose Collection.findAndModify: true

I'm currently working on implementing a user-to-user messaging feature within my NodeJS, Express, MongoDB application.

The approach I'm taking involves utilizing two MongoDB documents: 'Messages' to store individual messages and 'Conversations' to group related messages together.

Upon receiving a new message on the server, my goal is to search for existing conversations involving both the sender and recipient. If a relevant conversation is found, I aim to update it with the latest message. In case no such conversation exists, I need to create a new one and then add the message to it.

app.post('/messages', function(req, res){
  var message = { // Construct an object containing the message details
    sender: req.body.sender,
    recipient: req.body.recipient,
    messageContent: req.body.msgCont,
    timeSent: Date.now()
  };
  Message.create(message, function(err, newMessage){ // Save the message to MongoDB
    if(err){
      console.log('Error Creating Message' + Err);
    } else {
      console.log("The New Message " + newMessage)
      Conversation.findOneAndUpdate({ // Look for a conversation involving both users
        $and: [                       // as participants (there should only be one)
        {$or: [
          {"participants.user1.id" : req.body.sender},
          {"participants.user1.id" : req.body.recipient}
        ]},
        {$or: [
          {"participants.user2.id" : req.body.sender},
          {"participants.user2.id" : req.body.recipient}
        ]},
      ]}, {$setOnInsert : {
                            messages : message, 
                            "participants.user1.id" : req.body.sender,
                            "participants.user2.id" : req.body.recipient
                          },
      new : true,
      upsert : true
    }, function(err, convo){
        if(err){
          console.log(err + 'error finding conversation')
        } else {
          console.log("Convo " + convo)
        }
      });
    }
  });
  res.redirect('/matches');
});

Saving messages to the database functions correctly, but there seems to be an issue with the Conversation query. When checking the console, I receive Convo null, indicating that nothing is being added to the conversation document.

If anyone can spot where I might have made a mistake, any assistance would be greatly appreciated!

Answer №1

The method findOneAndUpdate in MongoDB does not support the option new. Instead, you should use returnNewDocument. Make sure to include curly brackets around these options.

{
  returnNewDocument: true,
  upsert: true
}

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 on verifying the count with sequelize and generating a Boolean outcome if the count is greater than zero

I'm currently working with Nodejs and I have a query that retrieves a count. I need to check if the count > 0 in order to return true, otherwise false. However, I am facing difficulties handling this in Nodejs. Below is the code snippet I am strugg ...

When using expressjs and typescript, you may encounter an error stating that the type 'typeof <express.Router>' cannot be assigned to the parameter type 'RequestHandlerParams'

Working on my project using expressjs with the latest typescript definition file and typescript 2.3.4 from https://github.com/DefinitelyTyped/DefinitelyTyped. I've set up a router and want to access it from a subpath as per the official 4.x documentat ...

Executing a function within a worker thread in Node.js

This is the worker I am using: const Worker = require('worker_threads'); const worker = new Worker("function hello () { console.log('hello world');}", { eval: true }) worker.hello() // this is incorrect I want to invoke the hello() fu ...

Automated algorithm inspecting a variety of hyperlinks

Recently, I've developed an innovative anti-invite feature for my bot. However, there seems to be a minor glitch where the bot fails to remove any links sent within the enabled guild when the command is triggered. This issue specifically occurs in ver ...

Error: npx is unable to locate the module named 'webpack'

I'm currently experimenting with a customized Webpack setup. I recently came across the suggestion to use npx webpack instead of node ./node_modules/webpack/bin/webpack.js. However, I am encountering some difficulties getting it to function as expecte ...

Utilizing node.js and sockets in my backbone application: a comprehensive guide

I have a question that I believe is fairly simple to answer. My node.js server is installed at /usr/local/bin/node The index.html and server.js files are located at /usr/local/bin When I run node, everything works fine. I have a chat application runni ...

How can Next JS automatically route users based on their IP address?

Currently, I am using express and the following method within app.get('/anyPath') to identify the IP address of the client: var ip = req.headers['x-real-ip'] || req.connection.remoteAddress if (ip.substr(0, 7) == "::ffff:") { ...

Learning the process of interpreting form data in Node.js

I'm currently working with Ionic Angular on the frontend and I am trying to send a formdata that includes a file along with two strings. It seems like the data is being sent successfully, but I am unsure how to access and read this information on the ...

Tips for sending formatted text (Bold, Italic, Line Breaks) to Android Skype for Business using Microsoft BotBuilder in Node.js

We have developed a chat Bot using Microsoft BotBuilder in Node.js to proactively send messages to Skype for Business users. Our goal is to send formatted text like Bold, Italic, and line breaks (new lines), but unfortunately, Android Skype for Business do ...

Error: Attempting to access 'props' property of undefined when clicking on a button within a React application leads to a TypeError

I'm currently working on implementing two buttons that will enable navigation to different pages within my React app. However, I encountered an error when attempting to use the button labeled "home." TypeError: Cannot read properties of undefined (rea ...

Encountering an issue where the sharp module fails to build during yarn install

After updating both Node and Yarn, I encountered an issue while trying to run yarn install on my NextJS project. The error message that showed up is as follows: ... ➤ YN0007: │ sharp@npm:0.29.3 must be built because it never has been before or the last ...

Exploring the combination of Express router, Auth0, and plain Javascript: A guide to implementing post-login authentication on a router

After creating a front end with vite using vanilla javascript and setting up a backend with node.js express routes, I successfully integrated swagger for testing purposes. I have managed to enable functionalities such as logging in, logging out, and securi ...

What is the method to display a value in an input field using ExpressJS?

Currently, I am delving into ExpressJS and have bootstrapped an application. While working on a basic login feature, I encountered a scenario where the user would enter the correct email but an incorrect password. In such cases, an error message for ' ...

Encountering difficulty in reaching the /login endpoint with TypeScript in Express framework

I'm currently working on a demo project using TypeScript and Express, but I've hit a roadblock that I can't seem to figure out. For this project, I've been following a tutorial series from this blog. However, after completing two parts ...

What distinguishes the sequence of events when delivering a result versus providing a promise in the .then method?

I've been diving into the world of Promises and I have a question about an example I found on MDN Web Docs which I modified. The original code was a bit surprising, but after some thought, I believe I understood why it behaved that way. The specific ...

What steps are needed to authenticate to Azure AD using NodeJS?

Currently, I am utilizing the activedirectory package from npm (https://www.npmjs.com/package/activedirectory). For reference, you can view an example from activedirectory here. I am having trouble determining the URL. I attempted it with my default Azure ...

MeanJS MongoDB insertion problem encountered

Currently, I am in the process of developing an application using MEANJS. The mongoose schema I have set up looks like this: var UserdetailSchema = new Schema({ fullName: { type: String, trim: true }, userName: { type: ...

Using Sequelize to update all values in a JSON file through an Express router.put operation

I've been working on a feature in my Express router that updates data in a MySQL schema for 'members' of clubs. The members table has various columns like member_id, forename, surname, address, etc. I've successfully created an Express ...

Building disconnected applications using Node.JS and CouchDB

Looking to create an app using node.js and considering options like couchdb, mongodb, or riak. I have a site called cool.com with a couchdb instance housing store data. The app has an admin backend for managing this data, but I want it to work offline as w ...

Establishing a server-side connection with Socket.io using Node.js

In my Node.js application, I have a frontend app and a backend app. The backend is responsible for managing the list and pushing updates to the frontend app. When I make a call to the frontend app, it triggers a list update so that all clients receive th ...