Javascript:删除json数组的成员

时间:2017-02-12 21:05:23

标签: javascript json

我的服务器应用程序(Node.js)返回前端用户列表(json数组)。但我也不想返回一些文件,如密码。所以这是我的用户模型代码:

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}
}));

我试图让经理不要转发某些领域,但没有积极的结果。这就是我尝试删除用户的数组对象的几个成员:

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);
        });
    },

前端接收所有字段(未应用过滤器)。 如果我使用不同的方式隐藏数据,例如:

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

而不是delete users[i].password等...它没有隐藏_id__v成员,而password字段被正确隐藏到前端({ {1}},因为它是布尔值,变为真。)

1 个答案:

答案 0 :(得分:1)

尝试将Projection参数添加到find函数:

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

并将您的回调作为第三个参数传递