The object persists in revealing the password that I am attempting to conceal

Seeking help to hide the password object from being displayed. Below is my code snippet where I am using bcrypt to hash the password. Even though I am trying to hide the return object, I am not seeing the desired outcome. Can someone please point out what I might be doing wrong? Any assistance would be greatly appreciated. Thank you.

var express = require('express')
var router = express.Router()
var User = require('../Models/User.js')
var bcrypt = require('bcrypt')

router.get('/:resource', function(req, res, next){
  var resource = req.params.resource

  if (resource == 'user'){
    User.find(null, function(err, users){
      if(err) {
        res.json({
          confimration: 'error',
          message: err
        })
        return
      }

        res.json({
          confimration: 'success',
          message: users
        })
        return
    })
  }
})

router.post('/:resource', function(req, res, next){
  var resource = req.params.resource
  var data = req.body
  var password = data.password
  var hashed = bcrypt.hashSync(password, 10)
  data['password'] = hashed

  if(resource == "user") {
    User.create(data, function(err, user){
      if(err){
        res.json({
          confirmation: 'fail',
          message: err
        })
        return
      }
      res.json({
        confirmation: 'success',
        result: user
      })
      return
    })
  }
})

module.exports = router



   var mongoose = require('mongoose')

    var UserSchema = new mongoose.Schema({
      firstName: {type: String, lowercase: true, trim: true, default: ''},
      lastName: {type: String, lowercase: true, trim: true, default: ''},
      email: {type: String, lowercase: true, trim: true, default: ''},
      city: {type: String, default: ''},
      password: {type: String, default: ''},
      timestamp: {type:Date, default: Date.now}
    })

    UserSchema.methods.summary = function() {
      var summary = {
        firstName: this.firstName,
        lastName: this.lastName,
        email: this.email,
        timestamp: this.timestamp,
        id: this._id,
        city: this.city
      }
      return summary
    }

    module.exports = mongoose.model('UserSchema', UserSchema)

{
_id: "57f460235805b52762605df2",
__v: 0,
timestamp: "2016-10-05T02:06:27.829Z",
password: "$2a$10$DIHrMO8WcRmOkIVj93SSQ.LFe5vPYH6R3xrfsSuql.v2jfU2mcO.C",
city: "new york",
email: "4",
lastName: "4",
firstName: "4"
}

Answer №1

When using router.get, consider utilizing a projection field. The inclusion of null is unclear, but the use of find in this context searches for all documents in the users collection while excluding the password field for each returned document. Could this be beneficial for your router.get implementation?

if (resource == 'user'){
    User.find({},{password: 0}, function(err, users){
      if(err) {
        res.json({
          confirmation: 'error',
          message: err
        })
        return
      }

      res.json({
        confirmation: 'success',
        message: users
      })
      return
    })
}

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

What steps should be taken to refresh an Expo app block once new data is retrieved from the database

I'm facing an issue with connecting my expo app to a database. I have utilized react redux to fetch data from the database, and upon successful retrieval of data, I aim to update my furniture block with the obtained information. However, despite recei ...

Having trouble with Socket.io and its io.emit() method refusing to work? If communication from server to client isn't going smoothly, you may need a solution for sending data from the server to

My latest project is a document converter program that utilizes LibreOffice to convert documents to PDF format. Here's my server running on localhost:3000 import express from "express"; import bodyParser from "body-parser"; import ...

Perform an action when the timer reaches zero

I am working with a database entry that contains the following information: { _id:"fdjshbjds564564sfsdf", shipmentCreationTime:"12:17 AM" shipmentExpiryTime:"12:32 AM" } My goal is to create a timer in the front end ...

Node.js console and endpoint are returning an object, but the JSON object cannot be fetched

Currently, I am working on a project for an online course where I am utilizing an NLP sentiment analysis API. Although I have made significant progress, I seem to be stuck at the final step. When I send the URL for analysis via the API call, I can see the ...

Bringing in a legacy ES5 module for integration within a ReactJS component

Attempting to incorporate an ES5 module into a new ReactJS application has been quite the challenge. I'm struggling with understanding the correct way to import the module so that the main function within it can be accessed and executed. Currently, m ...

Execute an AJAX function to monitor a JSON response at intervals of 3 seconds

I'm looking to verify if my user has been updated from another system using JavaScript. Can anyone assist me in creating a function that can analyze a JSON response and determine if it is true or false? The URL /user/updatecheck/ provides a JSON res ...

Multiple web pages utilizing Angular app/widget

I have successfully built a chat application similar to Google Hangouts. However, I am facing a challenge with the angular app/widget running on other pages when URL's are changed, causing the app to either remain fixed or restart on the new web page. ...

Tips for adding a scroll-to-top button on a page with only a vertical scroll bar

How can I make the scroll to top/bottom button only show up on pages with a vertical scrollbar? Currently, the button is not appearing when the page contains a vertical scrollbar. Any suggestions on how to implement this feature? ScrollToTopBottom.vue < ...

The performance of Jquery Animate is acting strangely after the upgrade to version 1.11

Take a look at http://jsfiddle.net/integerz/k19x8L1b/2/ which uses version 1.7.x $(function () { $("#clickme").toggle(function () { $(this).parent().animate({right:'0px'}); }, function () { $(this).parent().animate({righ ...

Pause for a minimum of 2 seconds after ajax has been completed before proceeding with transition.next() using Vue.js

For the smooth transition after completing an ajax call, I need to display the spinner for a minimum of 2 seconds. Below is my code, which unfortunately isn't functioning as expected: route: { data(transition) { this.getDelayedData(); ...

How to Create a Custom Callback Function for jQuery's .html

I am currently working with the following code: $.ajax({ type: 'GET', url: 'index.php?route=checkout/onepagecheckout/getpaypaldata', dataType: 'json', success: function(json) { ...

Encountering ENOENT error with Node.js file preview

I am attempting to utilize the filepreview tool to extract an image from a docx document. I have successfully installed it using the command npm install filepreview. This is the code snippet I am working with: const filepreview = require('fileprevie ...

Store the Ajax response in localStorage and convert it into an object for easy retrieval and manipulation

I'm currently working on an Ajax request that retrieves JSON data from the server and then stores it in localStorage for use in my application. However, I feel like my current code may not be the most efficient way to accomplish this task, as I have t ...

VSCode is experiencing issues with recognizing .env* files for markup purposes and is also failing to recognize .env.local.* files

Current Environment: Utilizing NextJs, React, and VsCode Noticing a problem with syntax highlighting in my VSCODE editor. I have installed the following extensions: ENV DotEnv As per suggestions, I updated my json configuration file as follows: " ...

Issue encountered while attempting to deactivate button until numerical data is entered in the OTP field using Vuejs

otp_value: '', isFadeout: false, verifyOtp() { this.disabled = true; this.otpBtnClicked = false; this.verified = true; }, <input class="o ...

Developing a Vue.js application with a universal variable

In the previous version of Vue.js, 0.12, passing a variable from the root component to its children was as simple as using inherit: true on any component that needed access to the parent's data. However, in Vue.js 1.0, the inherit: true feature was r ...

Switching the checkbox value upon clicking a div element

One challenge I am facing is with a checkbox that saves its value and title in the local storage when clicked. This checkbox is located within a div, and I want the checkbox value to change whenever any part of the div is clicked. Despite my efforts, I hav ...

Best practice for passing a variable argument in a JavaScript callback?

After searching the internet without success, I couldn't find the answer to my problem. The issue revolves around a function that I have: function ParentFunction (DataBase, Parameters) { for (k = 0; k < DataBase.length; k++){ var ...

Getting the value of "Page=?" from the href attribute in an HTML tag can be done using Selenium Webdriver and Java

I am looking to extract the value "page = ?" from a specific "href" tag in the HTML code below. I need this value for my Selenium WebDriver script so that my loop can iterate up to page 53. Can someone guide me on how to retrieve the "page =" value mentio ...

No data is being returned by the Jquery Ajax function

I am experiencing an issue with a Jquery Ajax call in my code: $('body').on('click', '#btnPopulate', function() { alert(getTree()); }); function getTree() { var url = getUrlPath() + "/StoryboardAdmin/BuildStoryboardViewMode ...