Mongoose: Find, modify, save


Question

I have a Mongoose User model:

var User = mongoose.model('Users',
    mongoose.Schema({
        username: 'string',
        password: 'string',
        rights: 'string'
    })
);

I want to find one instance of the User model, modify it's properties, and save the changes. This is what I have tried (it's wrong!):

User.find({username: oldUsername}, function (err, user) {
    user.username = newUser.username;
    user.password = newUser.password;
    user.rights = newUser.rights;

    user.save(function (err) {
        if(err) {
            console.error('ERROR!');
        }
    });
});

What is the syntax to find, modify and save an instance of the User model?

1
40
1/7/2013 4:01:59 PM

Accepted Answer

Why not use Model.update? After all you're not using the found user for anything else than to update it's properties:

User.update({username: oldUsername}, {
    username: newUser.username, 
    password: newUser.password, 
    rights: newUser.rights
}, function(err, numberAffected, rawResponse) {
   //handle it
})
48
1/7/2013 4:22:50 PM

The user parameter of your callback is an array with find. Use findOne instead of find when querying for a single instance.

User.findOne({username: oldUsername}, function (err, user) {
    user.username = newUser.username;
    user.password = newUser.password;
    user.rights = newUser.rights;

    user.save(function (err) {
        if(err) {
            console.error('ERROR!');
        }
    });
});

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon