Вопрос

I am setting up a server with Node and Express for the first time and am having trouble saving the response I am retrieving in my PUT call. This is a survey - I need to update the model with the "responded" object entered in the survey.

I do see the correct response outputting in the console but receive "Object [object Object],[object Object],[object Object],[object Object],[object Object] has no method 'findById'" from my "save" function.

Thank you in advance.

kitty-questions.json

[
{
    "id": "favorite-food",
    "number": "1",
    "url": "favorite-food",
    "name": "Favorite Food",
    "question": "Which of the following best describes your kitty's palatte?",
    "responded" : "default response",
    "query": "Which of the following best describes your kitty's palatte?",
    "answers": {
        "Grumpy" : "Fresh Water Salmon, no bones, served on china",
        "Hipster" : "Nothing - trying to fit into newer, tighter jeans",
        "Pudge" : "Anything and everything my owner is eating",
        "Bub" : "Mice",
        "Meow" : "Roaches"
    }
},
{
    "id": "favorite-band",
    "number": "2",
    "url": "favorite-band",
    "name": "Favorite Band",
    "question": "Your kitty claws at you desperatly when it wants to listen to:",
    "responded" : "default response",
    "query": "Which of the following best describes your kitty's palatte?",
    "answers": {
        "Bub" : "Country",
        "Grumpy" : "Mozart. Popular music is for the plebs.",
        "Pudge" : "z100",
        "Meow" : "Very heavy metal",
        "Hipster" : "something long winded"
    }
}

Server.js

var express = require('express'),
   http = require('http'),
   questions = require('./data/kitty-questions');

 var app = express()
  .use(express.bodyParser())
  .use(express.static('public'));

  app.get('/questions', function  (req, res) {
    res.json(questions);
  });

  app.post('/questions', function  (req, res) {
       var matches = questions.filter(function  (question) {
       return question.url === req.body.url;
    });

       if (matches.length > 0) {
          res.json(409, {status: 'question already exists'});
        } else {
           req.body.id = req.body.url;
           questions.push(req.body);
           res.json(req.body);
       }
   });

   app.put('/questions/:question_name', function (req, res) {
       var matches = questions.filter(function  (question) {
         return question.url === req.params.question_name;
   }); 

    var catResponse = req.body.responded;
     console.log(JSON.stringify(catResponse));

    return questions.findById(req.params.question_name, function (err, question) {
        question.catResponse = req.body.responded;
        return question.save(function (err) {
           if (!err) {
           console.log("updated");
           } else {
           console.log(err);
           }
       return res.send(question);
      });
   });    

  });

app.get('/questions/:question_name', function  (req, res) {
  var matches = questions.filter(function  (question) {
    return question.url === req.params.question_name;
});

  if (matches.length > 0) {
     res.json(matches[0]);
   } else {
    res.json(404, {status: 'invalid survey question'});
   }

 });

app.delete('/questions/:question_name', function  (req, res) {
  var found = false;
  items.forEach(function (question, index) {
      if (question.url === req.params.question_name) {
         found = index;
      }
   });

   if (found) {
      items.splice(found, 1);
      res.json(200, {status: 'deleted'});
    } else {
      res.json(404, {status: 'invalid survey question deletion'});
    }

   });


   app.get('/*', function  (req, res) {
     res.json(404, {status: 'not found'});
   });

  http.createServer(app).listen(3000, function () {
    console.log("Server ready at http://localhost:3000");
});

STRING FROM THE TERMINAL AFTER MAKING PUT CALL:

Server ready at http://localhost:3000

TypeError: Object [{"id":"favorite-food","number":"1","url":"favorite-food","name":"Favorite Food","question":"Which of the following best describes your kitty's palatte?","responded":"default response","query":"Which of the following best describes your kitty's palatte?","answers":{"Grumpy":"Fresh Water Salmon, no bones, served on china","Hipster":"Nothing - trying to fit into newer, tighter jeans","Pudge":"Anything and everything my owner is eating","Bub":"Mice","Meow":"Roaches"}},{"id":"favorite-band","number":"2","url":"favorite-band","name":"Favorite Band","question":"Your kitty claws at you desperatly when it wants to listen to:","responded":"default response","query":"Which of the following best describes your kitty's palatte?","answers":{"Bub":"Country","Grumpy":"Mozart. Popular music is for the plebs.","Pudge":"z100","Meow":"Very heavy metal","Hipster":"something long winded"}},{"id":"favorite-hideout","number":"3","url":"favorite-hideout","name":"Favorite Hideout","question":"You are most likely to find your beast perched here:","responded":"","answers":{"Bub":"On your shoulder","Grumpy":"Alone. Anywhere, just alone.","Pudge":"In the fridge","Meow":"Herding other cats","Hipster":"Outside, smoking."}},{"id":"favorite-friends","number":"4","url":"favorite-friends","name":"Favorite Friends","question":"Your kitty generally gets along with:","responded":"","answers":{"Bub":"Other cats","Grumpy":"No one.","Pudge":"Humans, animals, whoever.","Meow":"Obedient animals","Hipster":"dogs"}},{"id":"favorite-celebrity","number":"5","url":"favorite-celebrity","name":"Favorite Celebrity","question":"Your feline cannot get enough of this red carpet walker:","responded":"","answers":{"Bub":"Meg Ryan","Grumpy":"Jack Nicholson","Pudge":"John Candy","Meow":"Does General McArthur count?","Hipster":"Zooey Deschanel"}}] has no method 'update'

3/19 UPDATE:

 app.put('/questions/:question_name', function (req, res) {

      var question = questions.filter(function  (question) {
      return question.url === req.params.question_name;

   }); 

   var defaultResponse = question[0].responded;
   res.json(defaultResponse);

   var catResponse = req.body.responded;

    questions.update({id: req.params.question_name}, function (err, question) {
    question.catResponse = catResponse;

    question.save(function (err) {
       if (!err) {
           res.send(catResponse);
       } else {
          res.send(400); //or something
       }

     });
   });

 });    
Это было полезно?

Решение

There are a lot of unnecessary returns going on here, and at the very least, they make the code confusing to read.

Removing some stuff and ignoring the matches variable, since that isn't used in the PUT itself, something like this may be more what you're looking for:

app.put('/questions/:question_name', function (req, res) {

    var catResponse = req.body.responded;

    questions.update({id: req.params.question_name}, function (err, question) {
        question.catResponse = catResponse;

        question.save(function (err) {
           if (!err) {
               res.send(question);
           } else {
              res.send(400); //or something
           }

      });
   });    

});

*EDIT*

I assumed that questions = require('./data/kitty-questions'); was your mongoose model. You need questions to be a mongoose model for update to work.

Like:

var mongoose = require('mongoose')
, Questions = mongoose.model('Question')

Then your questions model file probably looks like:

var mongoose = require('mongoose');
var Schema   = mongoose.Schema;
var ObjectId = Schema.ObjectId;

QuestionSchema = new Schema({
    //keys and stuff in here

});

mongoose.model('Question', QuestionSchema);
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top