0

My server application (Node.js) returns to the front-end the users list (array of json). But I dont want to return also some fileds such as the password. So this is my user model code:

var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var config = require('../../config.js');

module.exports = mongoose.model(config.DATA_TYPE.USER, new Schema({
    username: String,
    password: String,
    admin: { type: Boolean, default: false},
    rate: { type: Number, default: 0},
    customers: { type: Number, default: 0},
    registration: { type: Date, default: Date.now}
}));

I'm trying by the manager to don't forward also some fields but without positive results. This is how I try to delete few members of the user's objects of the array:

var _ = require('lodash');
var User = require('../models/user.js');
var config = require('../../config.js');

var Manager = { 
    getUsers: function(callback){
        User.find({ admin : "false"}, function(err,users){
            for (i in users){
                delete users[i].admin;
                delete users[i].password;

                delete users[i]._id;
                delete users[i].__v;
            }
            callback(err,users);
        });
    },

The front-end receive all fields (no filter is applied). If I use a different way for hiding the data, for example:

    users[i].password = "xxx";
    users[i]._id = "xxx";
    users[i].__v = "xxx";
    users[i].admin = "xxx";

instead of the delete users[i].password etc... it is not hiding the _id and __v members, while password field is correctly hidden to the front-end (admin, since it is a boolean, becomes true).

0

1 Answer 1

1

try to add Projection argument to find function:

var Manager = { 
  getUsers: function(callback){
    User.find({ admin : "false"}, {_id: 0, __v: 0, admin: 0, password: 0}, callback);
  },

and just pass your callback as third argument

Sign up to request clarification or add additional context in comments.

1 Comment

This is exactly what I was looking for

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.