我在app.js中有这个代码,我将title
和content
字段的内容插入到MongoDB中各自的文档字段中:
//post to 'post/new'..
app.post('/post/new', function(req, res){
//get the `title` and `content` fields & save them as variables to be later reused (they rely on the `name:` values).
var title = req.body.title;
var content = req.body.content;
//call the database and find the `_id` to be used in the redirect later..
db.local.find({_id: ObjectId(req.params.id)}, function(id) {});
//insert the title and content in the database (taken from the submit form)
db.local.insert ( {title: title, content: content},
//not sure if I really need to define an err&doc right now so to be ignored..
function(err, doc) {
//redirect to "localhost.com/post/(post)_id/(post)title"
res.redirect('/post/'+req.params.id+'/'+req.body.title);
});
});
这就是post_new.ejs
上的内容:
<form method="post">
<div>
<div>
<span>Title :</span>
<input type="text" name="title" id="editPostTitle" />
</div>
<div>
<span>Content :</span>
<textarea name="content" rows="20" id="editPostBody"></textarea>
</div>
<div id='editPostSubmit'>
<input type="submit" value="Send" />
</div>
</div>
</form>
问题是我在res.redirect中得到的所有_id
都没有工作,这意味着,标题工作得非常好,但是_id no ..
如何让对象ID在重定向中起作用?谢谢!
修改 这是我得到的问题,并认为它是无关的..但我会将其包含在该问题的全部视图中。
500 Error: Argument passed in must be a single String of 12 bytes or a string of 24 hex characters
答案 0 :(得分:0)
假设您正在使用native node MongoDB driver,insert函数的回调将返回插入对象的数组。
这些文档中的示例非常好。调整你的例子,它会像这样:
var MongoClient = require('mongodb').MongoClient;
MongoClient.connect('mongodb://127.0.0.1:27017/test', function(err, db) {
db.collection('local').insert({title: title, content: content}, function(err, docs) {
console.log('Inserted _id is '+docs[0]._id);
});
});
关于您的错误,听起来req.params.id
不是有效的BSON ObjectId。