Nodejs Mongoose Saving model undefined is not a function

后端 未结 2 1708
夕颜
夕颜 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:25

    When you use in Mongoose the find method, it will return an array since it could discover one or many documents, so in your example you are querying to one specific element by its id, you should grab the first element on the returned array:

         Model.find({myId: myId}).exec(function (err, documents) {
                var model = documents[0];
    
                if (err) throw err;
                var fieldArray = model[0].fieldArray;
    

    Here is an example:

    var mongoose = require('mongoose');
    var Schema = mongoose.Schema;
    
    mongoose.connect('mongodb://localhost:27017/java-jedi');
    
    var HackerSchema = new Schema({
      name: String,
      languages: [String]
    });
    
    var Hacker = mongoose.model('Hacker', HackerSchema);
    
    
    // instantiating the model.
    var oneHacker = new Hacker();
    oneHacker.name = 'Richard Stallman';
    
    oneHacker.save(function(err) {
      if (err) throw err;
    
      // finding the document intentionally for this example
      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);
        });
      });
    
    });
    
    0 讨论(0)
  • 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!!

    0 讨论(0)
提交回复
热议问题