I am trying to use the "populate" function in mongoose to add song objects into playslists, but I can't get it working. When I create a new playlist, I only get:
{
"_id": "54f468a0c3242661233bf933d",
"id": 5,
"name": "test5",
"__v": 0,
"playlistsongs": []
}
]
Question: How does the populate function know which songs to add to the playlist?
song.js
/*
* Model for song
*/
// grab the mongoose module
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
//define schema
var songSchema = new Schema({
artist : { type: String, required: true },
title : {type: String, required: true},
genre : {type: String, required: true},
url : { type: String, required: true }
});
// define our model
// module.exports allows us to pass this to other files when it is called
module.exports = mongoose.model('Song', songSchema);
exports.Song = mongoose.model('Song', songSchema);
playlist.js
/*
* Model for playlist
*/
// grab the mongoose module
var mongoose = require('mongoose');
// create a new schema
var Schema = mongoose.Schema;
// define the schema
var playlistSchema = new Schema({
name : { type: String, required: true },
id : { type: Number, required: true},
playlistsongs : [{type: Schema.ObjectId, ref: 'Song'}]
});
// define our model
// module.exports allows us to pass this to other files when it is called
module.exports = mongoose.model('Playlist', playlistSchema);
routes.js
// route to get specific playlist
app.get('/api/playlists/:playlist_id', function(req, res, next) {
Playlist.findById(req.params.playlist_id, function(err, playlist) {
// if there is an error retrieving, send the error.
// nothing after res.send(err) will execute
if (err)
res.send(err);
Playlist.
find().
populate("playlistsongs").
exec(function(err, nws){
if(err) {res.writeHead(500, err.message)}
res.send(nws);
});
res.json(playlist); // return all playlists in JSON format
});
Aucun commentaire:
Enregistrer un commentaire