2014-03-05 13 views
0

我在我插入titlecontent字段的内容,以各自的文档字段MongoDB中app.js验证码:如何在Node.js(MongoJS)中捕获提交后的object_id?

//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> 

问题是,我得到的所有,但没有_id res.redirect工作,这意味着,标题的作品奇妙,但_id没有..

我怎样才能得到的对象T ID在重定向工作?谢谢!

编辑 这是我得到的问题,并认为它是无关的..但我会包括它的问题的全面看法。

500 Error: Argument passed in must be a single String of 12 bytes or a string of 24 hex characters 

回答

0

假设您使用的是native node MongoDB driver,则插入函数的回调将返回插入对象的数组。

这些文档中的例子是一个很好的例子。调整你的榜样,它想是这样的:

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

相关问题