Javascript Mongoose:查找、修改、保存

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14199529/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 15:59:38  来源:igfitidea点击:

Mongoose: Find, modify, save

javascriptnode.jsmongoose

提问by Randomblue

I have a Mongoose Usermodel:

我有一个猫鼬User模型:

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

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

我想找到User模型的一个实例,修改它的属性,然后保存更改。这是我尝试过的(这是错误的!):

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 Usermodel?

查找、修改和保存User模型实例的语法是什么?

回答by JohnnyHK

The userparameter of your callback is an array with find. Use findOneinstead of findwhen querying for a single instance.

user回调的参数是一个带有find. 在查询单个实例时使用findOne代替find

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!');
        }
    });
});

回答by soulcheck

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

为什么不使用Model.update?毕竟,除了更新其属性之外,您不会将找到的用户用于其他任何用途:

User.update({username: oldUsername}, {
    username: newUser.username, 
    password: newUser.password, 
    rights: newUser.rights
}, function(err, numberAffected, rawResponse) {
   //handle it
})

回答by Hyman blank

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 .markModifiedit worked.

我想补充一些非常重要的东西。我经常使用 JohnnyHK 方法,但我注意到有时更改不会保留到数据库中。当我使用.markModified它时,它起作用了。

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.

在保存之前使用 doc.markModified('pathToYourDate') 告诉猫鼬有关更改。

回答by Anthony Awuley

findOne, modify fields & save

findOne,修改字段并保存

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

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

另见updateOne

回答by Gulfaraz Rahman

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

如果您想使用find,就像我想在客户端进行的任何验证一样。

findreturns an ARRAY of objects

find返回一个 ARRAY 对象

findOnereturns only an object

findOne只返回一个对象

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

添加user = user[0]使保存方法对我有用。

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!');
        }
    });
});

回答by Deaconu Dan Andrei

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

您还可以使用 updateOne 和 $set 以及 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.

由于您不需要生成的文档,因此您可以使用 updateOne 而不是 findOneAndUpdate。

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

这里有一个关于差异的很好的讨论:MongoDB 3.2 - updateOne over findOneAndUpdate 的用例