Nodejs Mongoose Saving model undefined is not a function

后端 未结 2 1709
夕颜
夕颜 2021-01-01 01:55

I work with Nodejs Express routes and Mongoose to persist data. I did the core routes CRUD operations with no problem. However, when I try to perform some operations on one

2条回答
  •  孤城傲影
    2021-01-01 02:28

    OK guys! I want to thank Wilson Balderrama, because he basically pointed to the right direction.

    The code works! But let me clearify a bit.

      Hacker.find({_id: oneHacker._id}, function(err, hackers) {
    var hacker = hackers[0];
    
    // modifying the document and updating it.
    hacker.languages.push('Lisp');
    hacker.save(function(err) {
      if (err) throw err;
    
      console.log(hacker);
    });
    

    });

    So basically since the Model.find(.. returns an array
    when we save we have to grab the thing from array before saving.

    So corrected and final working version of my example will be:

        router.get('/:myId/:addThisToFieldArray', function(req, res, next) {
        var myId = req.params.myId;
        var addThisToFieldArray = req.params.addThisToFieldArray;
        Model.find({myId: myId}).exec(function (err, model) {
            if (err) throw err;
            var fieldArray = model[0].fieldArray;
            fieldArray.push("New thing to FieldArray");
            var newFieldArray = fieldArray;
            if (typeof newFieldArray === "object") model[0].fieldArray = newFieldArray;
            model[0].save(function (err, updatedModel){
                if (err) throw err;
                res.send(updatedModel);
            });
        });
    });
    

    Or we can use just Model.findOne(.. to avoid confusing ourselves with this arry return

    In this case we grab directly:

    router.get('/:myId/:addThisToFieldArray', function(req, res, next) {
    var myId = req.params.myId;
    var addThisToFieldArray = req.params.addThisToFieldArray;
    Model.findOne({myId: myId}).exec(function (err, model) {
        if (err) throw err;
        var fieldArray = model.fieldArray;
        fieldArray.push("New thing to FieldArray");
        var newFieldArray = fieldArray;
        if (typeof newFieldArray === "object") model.fieldArray = newFieldArray;
        model.save(function (err, updatedModel){
            if (err) throw err;
            res.send(updatedModel);
        });
    });
    });
    

    So in second case model[0].save(... becomes model.save(... direct grabbing and saving.

    Thank you Wilson Balderrama again!!

提交回复
热议问题