Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose: Find, modify, save

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?

like image 597
Randomblue Avatar asked Jan 07 '13 16:01

Randomblue


People also ask

What does save () do in Mongoose?

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.

How do I get the Objectid after I save an object in Mongoose?

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.

Does Mongoose save overwrite?

Mongoose save with an existing document will not override the same object reference. Bookmark this question.

What does find do in Mongoose?

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.


2 Answers

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!');         }     }); }); 
like image 153
JohnnyHK Avatar answered Oct 03 '22 03:10

JohnnyHK


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 }) 
like image 32
soulcheck Avatar answered Oct 03 '22 05:10

soulcheck