通过Mongoose的ObjectId查找MongoDB文档
我正在尝试通过ObjectId来查找MongoDB中的文档。 工作stream程如下(这是一个博客)。
- 通过传递标题和正文在MongoDB中创build一个新post。 ObjectId是自动创build的。
- 去编辑post。 它使用来自URL的ObjectId从数据库中获取数据,并以相同的新postforms显示它,只是使用预先存在的值。
- 当提交button被点击时,我想通过ObjectIdfind文档,并使用后表单中的值更新数据库中的值。
步骤1和2工作正常,但步骤3似乎并没有工作。 它redirect到我需要的页面。 但数据库尚未更新。 这和以前一样。
以下是更新post部分的相关代码:
app.js
app.post "/office/post/:id/update", ensureAuthenticated, routes.updatePost
路线/ 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);
这里是编辑博客post视图的代码:
app.js
app.get("/office/post/:id/edit", ensureAuthenticated, routes.editPost);
路线/ 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 }); }); }
问题是你如何调用update
return Post.update({ "_id": ObjectId.fromString(the_id) }, { "title": "CHANGE" }, res.redirect("/office/edit/posts"));
最后一个参数实际上会redirect页面,而update
需要在更新完成时调用一个函数
你应该通过
return Post.update({ "_id": ObjectId.fromString(the_id) }, { "title": "CHANGE" }, function(err, model) { if (err) // handleerr res.redirect("/office/edit/posts")); });
这样,一旦模型成功更新,我们只会redirect
- 如何使用快速validation器注册时validation用户名
- node.js / express不需要从当前页面redirect发送请求
- Angular / Node / Express / Passport – 连接到facebook(CORS)时的问题
- 当加载socket.io.js时,Node.js“Uncaught SyntaxError:Unexpected token <”
- app.configure(function){} typeerror undefined不是一个函数
- 护照令牌authentication*无*数据库会话
- 更新$ http返回数据到html视图
- mongoose不能保存embedded的文件
- 在Sequelize中不起作用