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

How to ensure an object is consistently rendered above all others using Three.js

Currently working on adding a dynamic command arrow that follows the cursor on the display. However, I have encountered an issue where it gets obscured by other elements on the screen. Is there a method to adjust the z-buffer or implement a workaround to ...

Map image showing only the tile layer in the top corner

My current project involves utilizing Ionic 5 and Vue.js. One of the screens in my project features a leaflet map that needs to cover most of the screen space. To implement this, I have integrated the Leaflet library for vue into my code. Here is a snippe ...

Special character Unicode regex for names

After spending the entire day reading about regex, I am still struggling to fully grasp it. My goal is to validate a name, but the regex functions I have found online only include [a-zA-Z], omitting characters that I need to allow. Essentially, I require ...

What is the rationale behind using both useMemo and createSelector in this code?

This example from the React-Redux documentation showcases how a selector can be utilized in multiple component instances while depending on the component's props. import React, { useMemo } from 'react' import { useSelector } from 'reac ...

What is the issue with the character set?

Attempting to send request data from JavaScript to Java using JSON format. In JavaScript, the request body appears as: { "id": "3", "name": "Chicken pasta", "description": "Lets make chicken pasta", "category": "Unassigned", "favorite" ...

Creating a HMAC-SHA-256 signature in JavaScript for datatrans: A step-by-step guide

I'm currently working on an Angular project that involves implementing the Datatrans payment system. Unfortunately, I have been facing difficulties in generating a sign for the payment. I have been following the process outlined in this link (enter l ...

What is the best way to handle multiple responses in Ajax within a single function?

Here is a simple code snippet: $.ajax({ url:'action.php', method: 'POST', data:{getcart:1}, success:function(response){ $('#getcart').html(response);//want to ...

Exploring the art of organizing and searching through documents in MongoDB

My data structure resembles the following: var city = { name: String, mayor: Person, citizens: [Person] }; I believe MongoDB would be a suitable choice for my use case. However, I have some concerns. The model above has been implemented using mongo ...

Real-time updates using Express.js and Redis

Looking for guidance on managing real-time changes from Redis in Express.js. I am in need of fresh data from Redis every time there is an update. Can someone provide a helpful example or solution for this? ...

navigate to a new page in vue with node.js

As I continue to expand my knowledge in JavaScript, Vue, and Node.js, I encountered a specific issue that I need help with. My goal is to redirect the Vue page after logging in using Node.js. Below you'll find the code snippets for my Vue setup and sc ...

Ways to verify if an ajax function is currently occupied by a previous request

Is there a way to determine if an ajax function is occupied by a prior call? What measures can be taken to avoid invoking an ajax function while it is still processing a previous request with a readyState != 4 status? ...

Ways to update the div's color according to a specific value

Below are the scripts and styles that were implemented: <script src="angular.min.js"></script> <style> .greater { color:#D7E3BF; background-color:#D7E3BF; } .less { color:#E5B9B5; background-co ...

Ways to receive JavaScript console error messages to aid in debugging your code

Currently, I am developing a Web Application and facing an issue with capturing console errors. Specifically, I need to capture errors related to network connectivity issues, such as when the network is down or slow causing responses from the server to be ...

Triggering an Ajax request by clicking on a link

In the scenario where you have a specific word on a webpage that you would like to trigger an onclick event and initiate an ajax request, what is the best approach to accomplish this? ...

Using services in Angular 6 CLI with dynamically added components

One of my recent projects involved creating a directive in Angular 6 called 'DeleteDirective' and integrating it with a service called 'DeleteService' to enable the deletion of items from the application. Once an item is deleted (handle ...

MySQL Entry Update Failure

This is the HTML/EJS code snippet: <div class="Edit-Panel" style="display: none;"> <div class="Edit-Wrapper"> <div class="Editing"> <p class="Edit-Header ...

Dynamic content for tooltips in Angular

Currently, I am facing a challenge where I need to dynamically populate content in a tooltip by executing a function with a parameter. This parameter holds the crucial information required to update the tooltip content. The complexity arises from the fact ...

Using jQuery's toggle function with a double click event to change the display to none

A div I created has the ability to expand to full screen upon double click, and I now wish to implement a toggle function so it can return to its original size when double clicked again. Initially, the code successfully increased the size of the div. Howe ...

ReactJS does not update the conditional CSS class when hovering with mouseOnEnter or mouseOnOver

I am currently attempting to showcase data in a table where each row features an info icon that is only visible upon hovering. Additionally, I want a pop-up to appear when the info icon is clicked (there is an onclick function assigned to this button). He ...

Troubleshooting the issue of onclick not functioning in JavaScript

My attempt to utilize onclick to trigger a function when the user clicks the button doesn't seem to be successful. For instance: function click(){ console.log('you click it!') } <input type='button' id='submitbutto ...