如何使用MongoDB,Node.js(+ express)和Jade创建MVC表单

时间:2013-03-27 04:53:57

标签: node.js mongodb express pug

我的任务是使用上面的堆栈创建一个简单的CRUD应用程序。

然而,我对它缺乏了解可能会妨碍我以更轻松的方式做事。

我主要关注的是更新。我有一个从数据库加载的对象(文档)。这些字段需要映射到表单中,当表单内容被修改和保存时,必须更新数据库。

我发现它很容易渲染,并使用JADE动态填充表单,但是,在回来的路上,我发现自己通过使用jQuery发送表单的字符串化JSON表示来“手动”重建对象;在将其存储回数据库之前。

是否有一些自动工具可以为我执行此映射? 给定一个JSON对象和一个表单,它将处理人口并将信息保存回模型。

作为参考,我来自SpringMVC + Hibernate背景。

指向教程甚至简单示例的指针都没问题。提前谢谢!

4 个答案:

答案 0 :(得分:1)

我一直在LocomotiveJS的创建者使用Passport

机车有猫鼬ORM support 您修改本地JS对象并调用save()进行更新 这符合您的需求吗?

以下是使用此设置进行博客的示例:
https://github.com/strongloop/sample-blog

答案 1 :(得分:1)

与其他人一样,我肯定会推荐MongooseJS。当我开始尝试学习类似的堆栈时,它帮助了我。在服务器上你可能有这样的东西:

// Define schema
var userSchema = mongoose.Schema(
    { name: 'string',
      description: 'string',
      email: 'string',
      date: { type: Date, default: Date.now },
    });

// Instantiate db model
var User = mongoose.model('User', userSchema);

// POST from client
exports.addUser = function (req, res) {

    // req.body contains the json from the client post
    // as long as the json field names are the same as the schema field names it will map the data automatically
    var newUser = new User(req.body); 

    newUser.save(function (err) {
      if(err) {
          return res.json({error: "Error saving new user"});
      } else {
        console.log("success adding new user");
        res.json(newUser);
      }

    });
};

// PUT from client
exports.updateUser = function(req, body) {
    // this contains the updated user json
    var updatedUser = req.body;

    // here we lookup that user by the email field
    User.findOne({ 'email': updatedUser.email }, function (err, user) {
      if(err) {
        return res.json({error: "Error fetching user" });
      }
      else {
        // we succesfully found the user in the database, update individual fields:
        user.name = updatedUser.name;
        user.save(function(err) {
            if(err) {
                return res.json({error: "Error updating user"});
            } else {
                console.log("success updating user");
                res.json(updatedUser);
            }
        })
      }
    });

};

编辑*显然,Mongoose实际上有一个findOneAndUpdate方法,它基本上和我上面写的更新模型一样。你可以阅读它here

答案 2 :(得分:0)

我不会使用jQuery在客户端构造JSON对象。最好将该实现留给服务器端。您可以从post变量轻松创建json对象并保存对象。另外,我不知道你是否需要这个,但是mongoose是一个很好的ODM(对象文档映射器),可以帮助你制作收集文档的模型。

答案 3 :(得分:0)

试试express-orm-mvc 一个支持express和orm with mvc template

的简单包