我正在尝试使用node,ember和mongodb创建一个能够编辑或删除数据库中现有歌曲的网页应用程序,该网页已经能够显示这些歌曲并添加新歌曲。当我单击歌曲旁边的“ EDIT”链接时会发生问题-当本应通过其ID来获取歌曲时,抛出“未捕获的TypeError:无法读取null的属性'id'”。
这是我的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}}
...
这是我的控制器/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();
}
}
});
...
答案 0 :(得分:1)
从您获得GitHub链接后,我发现您的代码有误,导致未知行为。
只需将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);