mongoose-bcrypt icon indicating copy to clipboard operation
mongoose-bcrypt copied to clipboard

Doesn't work on SubDocument with findOneAndUpdate and $push

Open christophrus opened this issue 5 years ago • 0 comments

It seems that the password doesn't get encrypted, when trying to $push a SubDocument with findOneAndUpdate.

Here is an example script:

var mongoose = require("mongoose");
mongoose.connect(process.env.MONGO_URI, { useNewUrlParser: true });
mongoose.set('useCreateIndex', true);
mongoose.set('useFindAndModify', false);


var Schema = mongoose.Schema;

var clientSchema = new Schema({
     name: {type: String},
     password: {type: String, bcrypt: true}
});

clientSchema.plugin(require('mongoose-bcrypt'));
var Client = mongoose.model('Client', clientSchema);

var resellerSchema = new Schema({
    name: {type: String},
    password: {type: String, bcrypt: true},
    clients: {type: [Client.schema], default: []}
});

resellerSchema.plugin(require('mongoose-bcrypt'));
var Reseller = mongoose.model('Reseller', resellerSchema);

var reseller = new Reseller({ name: 'reseller', password: '12345'});
var client1 = new Client({ name: 'Client1', password: '12345'});
var client2 = new Client({ name: 'Client2', password: '12345'});
reseller.clients.push(client1);

reseller.save((err, saved) => {
    Reseller.findOneAndUpdate({_id: saved._id}, {$push: {clients: client2}}, {new: true}, (err, updated) => {
        console.log(updated);
    });
});

Output:

{
    _id: 5cabd6022e7d5022c424c399,
    name: 'reseller',
    password: '$2a$10$s7vC4GVZKqEBzUuxceZUxONKlbP1/qpXtx5Dgcg4bBc3bdf12Mk0i',
    clients: [{
            _id: 5cabd6022e7d5022c424c39a,
            name: 'Client1',
            password: '$2a$10$tfNDW8QYGiYZv.mzb7BQeOd3ufRZubbP4HgdX2pINSDhshJ5IwTwq'
        },
        {
            _id: 5cabd6022e7d5022c424c39b,
            name: 'Client2',
            password: '12345'
        }
    ],
    __v: 0
}

Mongoose-Version: 5.5.0

christophrus avatar Apr 08 '19 23:04 christophrus