【问题标题】:Finding a MongoDB document by ObjectId with Mongoose使用 Mongoose 通过 ObjectId 查找 MongoDB 文档
【发布时间】:2013-02-06 04:17:15
【问题描述】:

我正在尝试通过 ObjectId 查找来更新 MongoDB 中的文档。工作流程如下(这是一个博客)。

  1. 通过传递标题和正文在 MongoDB 中创建新帖子。 ObjectId 是自动创建的。
  2. 去编辑帖子。它使用 URL 中的 ObjectId 从数据库中获取它,并将其显示在相同的新帖子表单中,只是使用预先存在的值。
  3. 单击提交按钮时,我想通过 ObjectId 查找文档,并使用 post 表单中的值更新数据库中的值。

第 1 步和第 2 步工作正常,但第 3 步似乎不起作用。它重定向到我需要它的页面。但是数据库还没有更新。与之前的值相同。

这里是更新帖子部分的相关代码:

app.js

app.post "/office/post/:id/update", ensureAuthenticated, routes.updatePost

routes/index.js

mongoose = require 'mongoose'
ObjectId = mongoose.Types.ObjectId

Post = require '../models/Post'

...

updatePost: function(req, res) {
  var o_id, the_id;

  the_id = req.params.id;
  console.log(the_id); // 510e05114e2fd6ce61000001

  o_id = ObjectId.fromString(the_id);
  console.log(o_id); // 510e05114e2fd6ce61000001

  return Post.update({
    "_id": ObjectId.fromString(the_id)
  }, {
    "title": "CHANGE"
  }, res.redirect("/office/edit/posts"));
}

我正在使用 Express 和 Mongoose。

如果有帮助,这也是帖子模型:

(function() {
  var Post, Schema, mongoose;

  mongoose = require('mongoose');

  Schema = mongoose.Schema;

  Post = new Schema({
    title: String,
    subhead: String,
    body: String,
    publish_date: {
      type: Date,
      "default": Date.now
    },
    mod_date: {
      type: Date,
      "default": Date.now
    }
  });

  module.exports = mongoose.model('Post', Post);

}).call(this);

这是编辑博客文章视图的代码:

app.js

app.get("/office/post/:id/edit", ensureAuthenticated, routes.editPost);

routes/index.js

editPost: function(req, res) {
  return Post.findById(req.params.id, function(err, post) {
    return res.render('edit-post', {
      post: post,
      title: post.title
    });
  });
}

【问题讨论】:

    标签: node.js mongodb express mongoose objectid


    【解决方案1】:

    问题在于你如何称呼update

    return Post.update({
        "_id": ObjectId.fromString(the_id)
    }, {
        "title": "CHANGE"
    }, res.redirect("/office/edit/posts"));
    

    最后一个参数实际上将重定向页面,而update 期望在更新完成时调用一个函数

    你应该通过

    return Post.update({
        "_id": ObjectId.fromString(the_id)
    }, {
        "title": "CHANGE"
    }, function(err, model) {
        if (err) // handleerr
    
        res.redirect("/office/edit/posts"));
    });
    

    这样,我们只在模型成功更新后重定向

    【讨论】:

    • 就是这样,谢谢!尽管对其他人来说,我也不得不改变引用_id的方式。这是 updatePost 的最终代码:updatePost: function(req, res) { return Post.update({ "_id": req.params.id }, req.body.post, function(err, post) { if (err) { console.log("Error"); } return res.redirect("/office/edit/posts"); }); }
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-01-06
    • 2015-06-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-06
    相关资源
    最近更新 更多