node.js - Finding a MongoDB document by ObjectId with Mongoose -
i trying update document in mongodb finding objectid. work flow follows (this blog).
create new post in mongodb passing title , body. objectid automatically created. go edit post. uses objectid url grab database , display in same new post form, preexisting values. when submit button clicked want find document objectid , update values in database in post form.step 1 & 2 work fine, step 3 doesn't seem working. redirects page need to. database has not been updated. it's same value before.
here's relevant code update post portion:
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 homecoming post.update({ "_id": objectid.fromstring(the_id) }, { "title": "change" }, res.redirect("/office/edit/posts")); }
i'm using express , mongoose.
this post model if helps:
(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);
and here's code edit blog post view:
app.js
app.get("/office/post/:id/edit", ensureauthenticated, routes.editpost);
routes/index.js
editpost: function(req, res) { homecoming post.findbyid(req.params.id, function(err, post) { homecoming res.render('edit-post', { post: post, title: post.title }); }); }
the problem how phone call update
return post.update({ "_id": objectid.fromstring(the_id) }, { "title": "change" }, res.redirect("/office/edit/posts"));
the lastly argument redirect page, whereas update
expects function called when update complete
you should pass in
return post.update({ "_id": objectid.fromstring(the_id) }, { "title": "change" }, function(err, model) { if (err) // handleerr res.redirect("/office/edit/posts")); });
that way, redirect 1 time model updated
node.js mongodb express mongoose objectid
No comments:
Post a Comment