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

标签 node.js mongodb express pug

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

但是,我对它缺乏了解可能会阻止我以更轻松的方式做事。

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

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

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

作为引用,我来自 SpringMVC+Hibernate 背景。

指向教程甚至简单示例的指针都可以。提前致谢!

最佳答案

和其他人一样,我肯定会推荐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

关于node.js - 如何使用 MongoDB、Node.js(+express) 和 Jade 创建 MVC 表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15652159/

相关文章:

javascript - 使用 [mongoose_model_object].save() 方法时 contact.save 不是函数错误

node.js - CORS预检 channel 未成功,React to Express

linux - 安装在服务器上的 MongoDB,连接 :0

javascript - 当我尝试将中间件函数导出到 module.exports 对象时,为什么会收到 'Next is not a function'?

javascript - 如何在 Node.js 中从 CouchDB 数据库获取文档

javascript - 如何在 JS 代理中拦截排序功能?

exception - 为什么使用nodejs上传异常

javascript - 如何自动创建 REST API node.js/MongoDB

javascript - 如何从 Mongoose 顺序检索数据?

node.js - 在 LoopbackJS : How to get server protocol (http or https) in a boot script or server side code? 中