Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using findOne then save() to replace a document, mongoose

I want to use the validation in my schema. Therefore i can't use findOneAndUpdate (?). I must use save.

Problem is, if I use findOne, then replaces the object with the one I'm going to replace it with, it will no longer have the save function.

mongoose.model('calculations').findOne({calcId:req.params['calcId']}, function(err, calculation){
    if(err) {errHandler.serverErr(err, res, 'Something went wrong when trying to update a calculation'); return;}
    calculation = calculationToReplace;
    calculation.save(function(err, calc){ //No longer exists
      if(err) {errHandler.serverErr(err, res, 'Something went wrong when trying to update a calculation'); return;}
      res.send(200);
    });
  });

This must be a common task but I can't find any solution. How do I fix this?

like image 312
Joe Avatar asked Mar 17 '23 22:03

Joe


1 Answers

There is a simple solution to your (by now really old) question. In my case I had to have a findOneAndUpdate upsert that returned more information on what happened. So my solution was to step through the process to update the object with a for loop.

(Think the reason why you can't just copy is that the doc object contains a bunch of "extras" like version information and save function and other "bits"); So here is my solution.

exports.postData = function(req,res) {
    console.log("will create " + req.body.alias);
    console.log("It is level " + req.body.level);     //OK, all this have to be changed to members of the data! req.body contains all the data sent from the user at this time
    var query = { 'fulltext' : req.body.fulltext};
    console.log("Checkking if " + req.body.fulltext + " exists")
    Skill.findOne(query, function (err,doc){
        if(err) return res.status(500).send(err)
        if (!doc){
            console.log(req.body.fulltext + " not found!")
            var newdoc = new Skill(req.body);
            newdoc.save(function(err){
                if(err) return res.status(500).send(err)
                console.log(newdoc.fulltext + " created as " + newdoc._id);
                return res.status(200).send({_id: newdoc._id, alias: newdoc.alias})
            })

            return res.status(200).send('blal')
        } else {
            console.log(req.body.fulltext + " found!")
            for (var id in req.body ){
                doc[id]= req.body[id];
            }
            doc.save( function(err){
                if(err) return res.status(500).send(err)
                return res.status(200).send({_id: doc._id, alias: doc.alias})
            })


            //return res.status(200).send({_id: doc._id, alias: doc.alias})
        }
like image 95
vrghost Avatar answered Mar 20 '23 15:03

vrghost