所以我跟着mongoose文件一起“加入”两张桌子。
http://mongoosejs.com/docs/populate.html
我有两个模式,第一个是专辑,第二个是流派。
我想从流派文档中提取所有类型,并仅填充流派名称和albumSchema。 当我点击端点查询相册时,我得到一个空对象,我跟踪文档中的所有内容,所以我不知道,请帮忙。
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;
});
}
那我到底错过了什么?
提前致谢。
答案 0 :(得分:1)
试试这个:
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;
});
}
保存:
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();