帆。如何更新模型

[英]sails.js: how to update model


Forgive my noob question. I'm using angularjs to send a user model (json) with varying fields. It works well with sails.js default PUT. I overrode the PUT, the problem is that I wish to update the model with the received JSON and do some processing on the modified model. Now I can't update the model with

原諒我的新手的問題。我正在使用angularjs發送一個具有不同字段的用戶模型(json)。它與帆配合得很好。js違約。我重寫了PUT,問題是我希望用接收到的JSON更新模型,並對修改后的模型進行一些處理。現在我無法更新模型

User.update({
id: req.body.id
},{
req.body
}, function(err, users) {
// Error handling
if (err) {
return console.log(err);
// Updated users successfully!
 } else {
console.log("Users updated:", users);
}
});

Please help

請幫助

EDIT: After knocking my head on the wall for days, problem solved! I know, my code formatting here is not the best..

編輯:把我的頭撞到牆上幾天后,問題解決了!我知道,我的代碼格式不是最好的。

changed this:

改變:

{
   req.body
  }

to just:

只:

req.body

(without the braces)

(沒有括號)

full snippet becomes:

完整的片段就變成:

User.update({
 id: req.body.id
},
req.body
, function(err, users) {
// Error handling
if (err) {
return console.log(err);
// Updated users successfully!
} else {
console.log("Users updated:", users);
}
 });

Thanks.

謝謝。

1 个解决方案

#1


13  

So you figured out your problem, sort of. req.body is already an object. But you really should sanitize it before you put it into your update and then save the object. There's a lot of reasons for this but with Mongo when you get only a partial object you'll replace the object in the collection which, in your example with a user, could be bad. When I send users to the frontend I cull off things I don't want transmitted all over like passwords. The other reason is the golden rule of web application development - never trust the client! I'd start with something like:

你算出了你的問題。要求的事情。身體已經是一個物體。但是,在將其放入更新並保存對象之前,您確實應該對其進行清理。這有很多原因,但是對於Mongo當你只得到一個部分對象時你會替換集合中的對象,在你的例子中,用一個用戶,這可能是不好的。當我將用戶發送到前端時,我將刪除所有我不希望被傳輸的東西,比如密碼。另一個原因是web應用程序開發的黃金規則——永遠不要信任客戶機!我首先要說的是:

var user = User.findOne(req.body.id).done(function(error, user) {
    if(error) {
        // do something with the error.
    }

    if(req.body.email) {
        // validate whether the email address is valid?

        // Then save it to the object.
        user.email = req.body.email;
    }
    // Repeat for each eligible attribute, etc.

    user.save(function(error) {
        if(error) {
            // do something with the error.
        } else {
            // value saved!
            req.send(user);
        }
    });
});

注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2013/09/13/72ff1e6d6b45bc712fe635f4792314cf.html



 
粤ICP备14056181号  © 2014-2021 ITdaan.com