Difficulty encountered with Mongoose/MongoDb FindOneAndUpdate functionality

My goal is to update a specific location only if it has a status of 0 or 2, but not if the status is 1. There is only one instance of this location in my database.

Property.findOneAndUpdate({ status: 0, location: req.body.update.location }, req.body.update, err => {
    if (err) return res.json({ success: false, error: err });
    return res.json({ success: true });
});
Property.findOneAndUpdate({ status: 2, location: req.body.update.location }, req.body.update, err => {
    if (err) return res.json({ success: false, error: err });
    return res.json({ success: true });
});

However, I noticed that the code above updates the property even when the status is 1.

Property.find({location: req.body.update.location}, (err, Propertyz) => {
    myProperty = Propertyz
    console.log(myProperty[0].status)
    if(myProperty[0].status != 1) { // returns and doesn't update if true
        console.log("updating")
        Property.findOneAndUpdate({ location: req.body.update.location }, req.body.update, err => {
            if (err) return res.json({ success: false, error: err });
            return res.json({ success: true });
        });
    }
    else {
        console.log("rejecting")
        return res.json({ success: true });
    }
})

I made some changes and now it works fine, although I still don't know why the previous version wasn't working as expected. I also wonder if there's a way to combine the two separate functions into one for efficiency.

Answer №1

      Update the location of a property if its status is either 0 or 2.
        Property.findOneAndUpdate({ $or: [{ status: 0, status: 2 }] }, { location: req.body.update.location }, err => {
          if (err) return res.json({ success: false, error: err });
          return res.json({ success: true });
        });

Answer №2

To update it, you can utilize a single findOneAndUpdate function by incorporating the $or operator in your query. Learn more about this operator at this link. The code below is designed to search for documents with status 2 or 0.

Property.findOneAndUpdate({ $or: [{status: 2}, {status: 0}], location: req.body.update.location }, req.body.update, err => {
if (err) return res.json({ success: false, error: err });
return res.json({ success: true });

Answer №3

When updating properties based on status and location, the following code snippet can be used:
Property.findOneAndUpdate({ status: 0, location: req.body.update.location }, { $set:req.body.update} , err => {
    if (err) return res.json({ success: false, error: err });
    return res.json({ success: true });
});
Property.findOneAndUpdate({ status: 2, location: req.body.update.location }, { $set:req.body.update} , err => {
    if (err) return res.json({ success: false, error: err });
    return res.json({ success: 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

I find myself struggling to manage my javascript dependencies

Currently, I am utilizing NPM along with various angular packages. As per the tutorial on Basic Grid Part 1 at this link, I am encountering challenges. This is my file directory structure: D:/nodeStuff/uiGrid includes: node_modules uigrid.css uigrid.h ...

After running the JavaScript function, the temporary display of textbox is initiated

I am trying to implement a feature where a textbox is shown or hidden when a user clicks on a filter icon in the header of a gridview. Initially, the textbox is hidden but when the icon is clicked, it briefly appears before disappearing again as if the pag ...

What is the best way to accurately determine the height and offset values of an element while utilizing ng-repeat?

My objective is to determine the offset and height of list items. Once I have those values, I trigger a function in a parent directive. Ultimately, this will involve transitioning elements in and out as they come into view. Issue: Due to the use of ng-rep ...

Having trouble with Chai-http functionality

Encountering an error message stating Uncaught TypeError: Cannot read property 'apply' of undefined at Immediate. (node_modules/express/lib/router/index.js:618:14) This pertains to both server and test files. // server js file 'use strict& ...

Implementing dynamic ID routes in React Router using JSON data

As a beginner in React, I have been working hard to improve my skills every day. However, I am currently facing a challenge with creating dynamic routes using JSON characters (specifically from Dragon Ball Z). Although my routes are set up correctly, I wo ...

Is there a way to modify an existing job in Kue Node.js after it has been created?

Utilizing Kue, I am generating employment opportunities. jobs.create('myQueue', { 'title':'test', 'job_id': id ,'params': params } ) .delay(milliseconds) .removeOnComplete( true ) ...

What is the best way to output multiple Div elements using Jquery or Javascript?

I have the following HTML code snippet: <div id="box"> <div id="id_1></div> <div id="id_2></div> <div id="id_3></div> <div id="id_4></div> </div> Can someone guide me on how to use Jquery or ...

What's the best way to keep track of the number of objects I've created

Using this HTML code, I can create member objects. However, I also need to determine the count of these member objects for certain calculations. Additionally, when a member object is deleted, the count of member objects should be reduced accordingly. The ...

Issues with broadcasting in React using Socket IO have arisen

Currently, I am developing a game using Socket IO where each room has its own channel of communication. The issue I am facing is that when a player places a bet, not only does the opponent receive the message, but the player themselves also receives it. B ...

I'm facing a challenge with displaying data on a dynamically created table using VueJS

I'm having an issue with dynamically generating a table using VueJS. The problem arises when creating the <th> elements. In order to set them up, I have a Vue component that is called by the addRow function. This component uses templates with v ...

What is the process for determining the files array in the nx dep-graph?

With each new release of NX v16.1.4, the file node_modules/.cache/nx/nxdeps.json is created. The structure of this file differs from the one generated by nx graph. In previous versions up to 16.1., the file contained an array named nodes.<app/lib>.d ...

Achieving the perfect alignment: Centering a paragraph containing an image using JQuery

I need help centering the background image of my <p> tag on the webpage. Script $(function() { $('ul.nav a').bind('click', function(event) { var $anchor = $(this); $('html, body').stop().animate({ ...

I am looking to incorporate friendship features into my database using sequelize for a social media demo application - how should I

Currently, I am in the process of creating a social media demonstration application that incorporates friend functionality. My plan is to create a new table (model in sequelize) in the database which will include the ids of two users (user1 and user2) alon ...

Pick the item when the checkbox is selected

I am currently attempting to toggle the visibility of a select element based on whether a checkbox is checked or not, but it doesn't seem to be working as expected. My desired functionality is for the select element to be hidden upon page load and th ...

Troubleshooting steps for resolving Heroku's "State changed from up to crashed" error caused by Mongoose connection issue

I am encountering an issue while deploying my Node.js/MongoDB app to Heroku. It crashes with the following error: MongooseServerSelectionError: connection <monitor> to 104.155.184.217:27017 closed Below are excerpts from my log: 2022-07-10T23:36:17. ...

Determine the presence of a value within an array in mongodb

How can I determine if the current Meteor.user()._id exists in the "favoritedBy" array? If true, display "Your favorite", if false, display "Not your favorite". Here is an example document in MongoDB: { "_id" : "W5WwAZatorDEb6DNP", "createdBy" : "aT ...

Maintain checkbox selection even after leaving the page

I am looking for a way to maintain the state of a checkbox even after navigating away from the page in an AngularJS and bootstrap environment. Currently, I find that my bound variable gets reset to false every time I reload the page when the controller run ...

What is the best way to incorporate an ASYNC function within a .map function to dynamically populate a table in a REACT application?

I am attempting to use the .map() method in REACT to call an async function and populate table data cells. The async function communicates with the backend of my application using data from the array being looped through. When called correctly, the functi ...

Make sure to validate a form when submitting from an external source rather than through an HTML

In my form, there are various input fields (some acting as inputs even if they're not). Each field is validated upon submission by angular validation and html attributes like required, ng-maxlength, minlength, etc. Now, we want to implement a keyboar ...

The Express server effortlessly included a vulnerable ETAG

Exploring HTTP caching, I developed a basic Express node.js server to experiment with different caching mechanisms. const express = require('express') const serveStatic = require('serve-static') const path = require('pa ...