gpt4 book ai didi

javascript - Mongoose 不加入两个集合

转载 作者:行者123 更新时间:2023-11-30 20:26:09 25 4
gpt4 key购买 nike

所以我正在按照 mongoose 文档将两个表“连接”在一起。

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

我有两个模式,第一个是专辑,第二个是流派。

我想从流派文档中提取所有流派,并仅填充流派名称和 albumSchema。当我点击端点查询相册时,我得到一个空对象,我按照文档中的所有内容进行操作,所以我不知道,请帮忙。

相册.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);

流派.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);

专辑 Controller .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;
});

}

那么我到底错过了什么?

提前致谢。

enter image description here

最佳答案

试试这个:

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();

关于javascript - Mongoose 不加入两个集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50902522/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com