首页 文章

使用Mongoose通过ObjectId查找MongoDB文档

提问于
浏览
8

我试图通过ObjectId找到它来更新MongoDB中的文档 . 工作流程如下(这是针对博客) .

  • 通过传递 Headers 和正文在MongoDB中创建一个新帖子 . ObjectId是自动创建的 .

  • 转到编辑帖子 . 它使用URL中的ObjectId从数据库中获取它,并将其显示在相同的新帖子表单中,只显示预先存在的值 .

  • 单击提交按钮时,我想通过ObjectId查找文档,并使用post表单中的值更新数据库中的值 .

第1步和第2步工作正常,但第3步似乎不起作用 . 它重定向到我需要它的页面 . 但数据库尚未更新 . 它与以前的 Value 相同 .

以下是更新帖子部分的相关代码:

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

1 回答

  • 3

    问题是你如何调用 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"));
    });
    

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

相关问题