Finding a MongoDB ObjectId Document Using Mongoose

I am trying to update a document in MongoDB by finding its ObjectId. The workflow is as follows (this is for the blog).

  • Create a new message in MongoDB, passing the header and body. ObjectId is automatically created.
  • Go to edit the message. It uses the ObjectId from the URL to grab it from the database and display in the same new message form as the previous values.
  • When the submit button is clicked, I want to find the ObjectId document and update the values โ€‹โ€‹in the database with the data in the form of a message.

Step 1 and 2 work fine, but step 3 doesn't seem to work. It redirects to the page that I need. But the database was not updated. This is the same value as before.

Here is the appropriate code for the update message part:

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 return Post.update({ "_id": ObjectId.fromString(the_id) }, { "title": "CHANGE" }, res.redirect("/office/edit/posts")); } 

I use Express and Mongoose.

It is also a publishing model if it 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 is the code for editing the blog:

app.js

 app.get("/office/post/:id/edit", ensureAuthenticated, routes.editPost); 

routes /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 }); }); } 
+8
mongodb mongoose express objectid
source share
1 answer

The problem is how you call update

 return Post.update({ "_id": ObjectId.fromString(the_id) }, { "title": "CHANGE" }, res.redirect("/office/edit/posts")); 

The last argument actually redirects the page, while update expects the function to be called when the update completes.

You have to go through

 return Post.update({ "_id": ObjectId.fromString(the_id) }, { "title": "CHANGE" }, function(err, model) { if (err) // handleerr res.redirect("/office/edit/posts")); }); 

Thus, we redirect only after a successful update of the model.

+3
source share

All Articles