Mongoose: Find, modify, save

后端 未结 6 520
不思量自难忘°
不思量自难忘° 2020-11-28 06:49

I have a Mongoose User model:

var User = mongoose.model(\'Users\',
    mongoose.Schema({
        username: \'string\',
        password: \'strin         


        
相关标签:
6条回答
  • 2020-11-28 06:59

    findOne, modify fields & save

    User.findOne({username: oldUsername})
      .then(user => {
        user.username = newUser.username;
        user.password = newUser.password;
        user.rights = newUser.rights;
    
        user.markModified('username');
        user.markModified('password');
        user.markModified('rights');
    
        user.save(err => console.log(err));
    });
    

    OR findOneAndUpdate

    User.findOneAndUpdate({username: oldUsername}, {$set: { username: newUser.username, user: newUser.password, user:newUser.rights;}}, {new: true}, (err, doc) => {
        if (err) {
            console.log("Something wrong when updating data!");
        }
        console.log(doc);
    });
    

    Also see updateOne

    0 讨论(0)
  • 2020-11-28 07:05

    If you want to use find, like I would for any validation you want to do on the client side.

    find returns an ARRAY of objects

    findOne returns only an object

    Adding user = user[0] made the save method work for me.

    Here is where you put it.

    User.find({username: oldUsername}, function (err, user) {
        user = user[0];
        user.username = newUser.username;
        user.password = newUser.password;
        user.rights = newUser.rights;
    
        user.save(function (err) {
            if(err) {
                console.error('ERROR!');
            }
        });
    });
    
    0 讨论(0)
  • 2020-11-28 07:06

    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
    })
    
    0 讨论(0)
  • 2020-11-28 07:09

    You could also write it a little more cleaner using updateOne & $set, plus async/await.

    const updateUser = async (newUser) => {
      try {
        await User.updateOne({ username: oldUsername }, {
          $set: {
            username: newUser.username,
            password: newUser.password,
            rights: newUser.rights
          }
        })
      } catch (err) {
        console.log(err)
      }
    }
    

    Since you don't need the resulting document, you can just use updateOne instead of findOneAndUpdate.

    Here's a good discussion about the difference: MongoDB 3.2 - Use cases for updateOne over findOneAndUpdate

    0 讨论(0)
  • 2020-11-28 07:15

    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!');
            }
        });
    });
    
    0 讨论(0)
  • 2020-11-28 07:22

    I wanted to add something very important. I use JohnnyHK method a lot but I noticed sometimes the changes didn't persist to the database. When I used .markModified it worked.

    User.findOne({username: oldUsername}, function (err, user) {
       user.username = newUser.username;
       user.password = newUser.password;
       user.rights = newUser.rights;
    
       user.markModified(username)
       user.markModified(password)
       user.markModified(rights)
        user.save(function (err) {
        if(err) {
            console.error('ERROR!');
        }
    });
    });
    

    tell mongoose about the change with doc.markModified('pathToYourDate') before saving.

    0 讨论(0)
提交回复
热议问题