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?
Mongoose | save() Function The save() function is used to save the document to the database. Using this function, new documents can be added to the database.
To get the object ID after an object is saved in Mongoose, we can get the value from the callback that's run after we call save . const { Schema } = require('mongoose') mongoose. connect('mongodb://localhost/lol', (err) => { if (err) { console. log(err) } }); const ChatSchema = new Schema({ name: String }); mongoose.
Mongoose save with an existing document will not override the same object reference. Bookmark this question.
Mongoose | findOne() Function The findOne() function is used to find one document according to the condition. If multiple documents match the condition, then it returns the first document satisfying the condition.
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!'); } }); });
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 })
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With