猫鼬:查找,修改,保存 [英] Mongoose: Find, modify, save

查看:99
本文介绍了猫鼬:查找,修改,保存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Mongoose 用户型号:

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

查找,修改和保存用户实例的语法是什么 model?

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

推荐答案

为什么不使用 Model.update ?毕竟你没有使用找到的用户除了更新它的属性:

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
})

这篇关于猫鼬:查找,修改,保存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆