How to fix Uncaught TypeError: Cannot read property 'id' of null in node?

How to fix Uncaught TypeError: Cannot read property 'id' of null in node?

我正在尝试使用节点创建一个网页应用程序,ember 和 mongodb 能够编辑或删除我数据库中的现有歌曲,该网页已经能够显示歌曲并添加新歌曲。当我点击歌曲旁边的 "EDIT" link 时出现问题 - 当它应该通过它的 id 为我获取歌曲时它会抛出 "Uncaught TypeError: Cannot read property 'id' of null"。

这是我的 app/routes.js 代码:

...
router.route('/songs/:song_id')
 .put(function(req, res) { songs.updateSong(req, res, req.params.song_id) })
 .delete(function(req, res) { songs.deleteSong(req, res, req.params.song_id) });
...

这是我的 api/song.js 代码:

...
module.exports.findById = function(req, res) {
  console.log(req.params.id);
  Song.findById(req.params.id ,function(err, data){
    if(err){console.log(err);}
    console.log(data);
    return res.send({
      song: data
    });
  });
};
...

这是我的 app/router.js 代码:

...
var SongSchema = new mongoose.Schema({
  title: String,
  artist: String,
  year: Number,
  genre: String,
  lyrics: String
});
...
app.get('/api/songs/:id', function(req, res){
  console.log(req.params.id);
  Song.findById(req,res ,function(err, docs){
    if(err) res.send({error:err});
    else res.send({data:docs, "Song":"song"});
  });
});
...

templates/song.hbs

...
{{#each model as |song|}}
  <li>
    <b>{{song.artist}} - {{song.title}}  {{#link-to 'edit' song.id}}EDIT{{/link-to}} </b><br>
    ID:<i>{{song._id}}</i> <br>
    Released: {{song.year}} <br>
    Genre: {{song.genre}} <br>
    Lyrics:<br> "{{song.lyrics}}"<br><br>
   </li>
{{/each}}
...

这是我的 controllers/edit.js

...

export default Ember.Controller.extend({
  actions: {
    save: function() {
      var d = this.get('model');
      d.save();
      this.transitionToRoute('song');
    },
    del: function() {
      this.get('model').deleteRecord();
      this.transitionToRoute('song');
      this.get('model').save();
    }
  }
});
...

从你那里得到 GitHub link 后,我发现你的代码有错误导致了未知行为。

只需将app/routes.js替换为以下内容:

const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const SongsController = require('../api/songs');

const SongSchema = new mongoose.Schema({
  title: String,
  artist: String,
  year: Number,
  genre: String,
  lyrics: String
});

const Song = mongoose.model('song', SongSchema);

module.exports = (app) => {

  app.get('/api/songs', async (req, res) => {
    try {
      const songs = await Song.find({}).lean();
      res.status(200).send({songs});
    } catch(error) {
      res.status(500).send({
        message: error.message
      });
    }
  });

  app.get('/api/songs/:id', async (req, res) => {
    try {
      const song = await Song.findById(req.params.id).lean();
      if(!song) {
        return res.status(404).send({
          message: "Song not found",
          params: req.params
        });
      }
      res.status(200).send({song});
    } catch(error) {
      res.status(500).send({
        message: error.message
      });
    }
  });


  app.use(bodyParser.urlencoded({extended: false}));

  app.post('*', SongsController.addSong);
};

P.S。快速修复只是将处理传递给已经编写的 SongsController.findById 方法:

app.get('/api/songs/:id', SongsController.findById);