admin管理员组

文章数量:1289702

Looking for a way to remove object properties before sending them to the front-end.
Is there any reason why this is working:

var obj = {
    name: 'cris',
    age: 22,
}
console.log(obj) //output name, age
delete obj.name
console.log(obj) //output age

and this isn't:

User.findOne({ username: req.query.username }, function (err, user) {
    if (user != null) {
        console.log(user) //output all props
        delete user.salt || delete user['salt']
        console.log(user) //output all props
    } 
});

Looking for a way to remove object properties before sending them to the front-end.
Is there any reason why this is working:

var obj = {
    name: 'cris',
    age: 22,
}
console.log(obj) //output name, age
delete obj.name
console.log(obj) //output age

and this isn't:

User.findOne({ username: req.query.username }, function (err, user) {
    if (user != null) {
        console.log(user) //output all props
        delete user.salt || delete user['salt']
        console.log(user) //output all props
    } 
});
Share Improve this question asked May 23, 2017 at 7:24 Cristian MuscaluCristian Muscalu 9,93512 gold badges48 silver badges85 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 7

user is a Mongoose document and not a regular object.

You can convert it to one using toObject():

user = user.toObject();

to use delete you would need to convert the model document into a plain JavaScript object by calling toObject:

User.findOne({ username: req.query.username }, function (err, user) {
    if (user != null) {
        console.log(user) //output all props
        user = user.toObject();
        delete user.salt || delete user['salt']
        console.log(user) //remove salt prop
    } 
});

also you can modify uses this

User.findOne({}, function(err, user){
  user.key_to_delete = undefined;
  user.save();
});

Mongoose is returning an instance of model and not a plain JS object you are looking for. The data you are looking for that can be accessed by using user.toObject().

The db.collection.findOne() method returns a cursor. you need to convert to object using toObject(). use user.toObject() and then delete and send it to client.

本文标签: javascriptmongoose removing properties from objectStack Overflow