简体   繁体   English

猫鼬没有加入两个集合

[英]Mongoose not joining two collections

So I am following the mongoose document to "join" two table together.所以我按照猫鼬文档将两个表“连接”在一起。

http://mongoosejs.com/docs/populate.html 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相册.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流派.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相册控制器.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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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