ptf
ptf

Reputation: 3370

Load and save document in mongodb with mongoose

I have node running with express as the server side framework.

I have created the following endpoint:

app.post('/post/save', auth.auth, function (req, res) {

Post.findById(req.body._id, function (err, post) {
  post = post || new Post();

  post.author.name = req.user.getName();
  post.author.id = req.user._id;
  post.title = req.body.title;
  post.body = req.body.body;

  post.save(function (err, object) {
    err && res.send(500);
    res.status(200).send({ /*id: object._id*/ });
  });  
});

});

When I call this the first time, it works. When I call this the second time, it fails. The request just keeps pending, and the object returned from the save function call is undefined.

req.body._id is undefined in both the requests. I try to create 2 new posts in a row.

What I want to do is to check if a document exist, if it does, update it and then save it, or create a new document.

I know stuff like upsert exist, but I cant use it because I need the pre-save middleware to trigger, and it only triggers before .save.

Can anyone see the error?

Upvotes: 0

Views: 196

Answers (2)

ptf
ptf

Reputation: 3370

My original post worked, once I removed the unique field from the model, and dropped the collections in the database.

It might have been enough to drop the indexes; see Leonid Beschastnys comment;

when you're setting a field to be unique, Mongoose creates an unique index on this field. This index persist in MongoDB even after removing unique: true flag. Dropping collection indexes should resolve your problem

Upvotes: 0

Vitalii Zurian
Vitalii Zurian

Reputation: 17976

What if you put your logic to a callback, and then - either create or find a Post based on the request query value, passing your callback function? Just dont forget to remove this assignment: post.author.id = req.user._id;

app.post('/post/save', auth.auth, function (req, res) {
    var callback = function(post) {
      post.author.name = req.user.getName();
      post.title = req.body.title;
      post.body = req.body.body;

      post.save(function (err, object) {
        err && res.send(500);
        res.status(200).send({ /*id: object._id*/ });
      });  
    };

    if (req.body._id) {
        Post.findById(req.body._id, function (err, post) {
            callback(post);
        });        
    } else {
        var post = new Post();
        callback(post);
    }
});

Upvotes: 1

Related Questions