简体   繁体   中英

Mongoose not joining two collections

So I am following the mongoose document to "join" two table together.

http://mongoosejs.com/docs/populate.html

I have two schemas, the first one is an album and the second one is a genre.

I want to pull all the genres from genre document and populate only the genre name along with the albumSchema. I am getting an empty object when I hit the endpoint to query the album, I followed everything in the document so I have no idea, please help.

Album.js

var mongoose = require('mongoose');
var moment = require('moment');

var AlbumSchema = new mongoose.Schema({
    artist: { type: String, default: ''},
    genre: { type: String, default: ''},
    info: { type: String, default: ''},
    title: { type: String, default: ''},
    label: { type: String, default: ''},
    tracks: { type: String, default: ''},
    cover: { type: String, default: ''},
    genreDetails: [{type: mongoose.Schema.Types.ObjectId, ref: 'Genre'}],
    timestamp: {type: String, default: () => moment().format("dddd, MMMM Do YYYY, h:mm:ss a") }
});

module.exports = mongoose.model('Album', AlbumSchema);

Genre.js

var mongoose = require('mongoose');
var moment = require('moment');

var GenreSchema = new mongoose.Schema({
    name: { type: String, unique: true, default: ''},
    timestamp: {type: String, default: () => moment().format("dddd, MMMM Do YYYY, h:mm:ss a") }
});

module.exports = mongoose.model('Genre', GenreSchema);

AlbumController.js

getAlbumDetailsAndGenres: function(id, callback) {
    Album.findById(id)
          .populate({path: 'genreDetails', select: 'name'})
          .exec(function(err, result) {
            if (err) {
                callback(err, null);
                return;
            }
            callback(null, result);
            return;
          });

}

So what exactly am I missing?

Thanks in advance.

在此处输入图片说明

try this one :

getAlbumDetailsAndGenres: function(id, callback) {
     Album.findOne({_id:new mongoose.mongo.ObjectID(id)})
          .populate('genreDetails','name')
          .exec(function(err, result) {
            if (err) {
                callback(err, null);
                return;
            }
            callback(null, result);
            return;
          });

}

to save :

genreDetails=[];

genreDetails.push(new mongoose.mongo.ObjectID('....id..here...'));


var album = new Album({
  artist:"Aerosmith",
  gerne:"Rock N Roll",
  info:"Blar",
  title:"I dont want to miss a thing",
  label:"Sony",
  tracks:10,
  cover:"Aerosmith",
  genreDetails:genreDetails
});

album.save();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM