Dav*_*ser 8 mongoose mongodb node.js express objectid
我试图通过ObjectId找到它来更新MongoDB中的文档.工作流程如下(这是针对博客).
第1步和第2步工作正常,但第3步似乎不起作用.它重定向到我需要它的页面.但数据库尚未更新.它与以前的价值相同.
以下是更新帖子部分的相关代码:
app.js
app.post "/office/post/:id/update", ensureAuthenticated, routes.updatePost
Run Code Online (Sandbox Code Playgroud)
路线/ 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"));
}
Run Code Online (Sandbox Code Playgroud)
我正在使用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);
Run Code Online (Sandbox Code Playgroud)
以下是编辑博客帖子视图的代码:
app.js
app.get("/office/post/:id/edit", ensureAuthenticated, routes.editPost);
Run Code Online (Sandbox Code Playgroud)
路线/ 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
});
});
}
Run Code Online (Sandbox Code Playgroud)
问题是你如何调用update
return Post.update({
"_id": ObjectId.fromString(the_id)
}, {
"title": "CHANGE"
}, res.redirect("/office/edit/posts"));
Run Code Online (Sandbox Code Playgroud)
最后一个参数实际上会重定向页面,而update期望更新完成时调用一个函数
你应该通过
return Post.update({
"_id": ObjectId.fromString(the_id)
}, {
"title": "CHANGE"
}, function(err, model) {
if (err) // handleerr
res.redirect("/office/edit/posts"));
});
Run Code Online (Sandbox Code Playgroud)
这样,我们仅在模型成功更新后重定向
| 归档时间: |
|
| 查看次数: |
32861 次 |
| 最近记录: |