【发布时间】:2020-11-19 02:56:01
【问题描述】:
这是我的架构,我没有定义 _id 字段,所以它是由 mongoose 创建的,它的类型是 ObjectId,这就是它在 robo3T 中的显示方式
/*
Copyright (c) 2020 Antonio Roldan
All rights reserved
*/
import mongoose, { Schema } from 'mongoose'
import { IAlbum } from '../interfaces/IAlbum'
const albumSchema = new Schema({
title: {
type: String,
required: true,
minlength: 1,
trim: true
},
authorId: { // We create an array to allow collaborations
type: mongoose.Schema.Types.ObjectId
},
authorName: {
type: String
},
coverUrl: { // Reference to album's image file stored in a gridFS collection
type: String
},
genres: [{
type: String,
required: true,
trim: true
}],
releaseDate: {
type: Date,
default: Date.now
},
isPremium: {
type: Boolean,
default: false
}
})
export default mongoose.model < IAlbum > ('Album', albumSchema)
这里是我进行调用的地方,注意我传递的是字符串而不是 ObjectId,我尝试使用 objectId 但它仍然不起作用
public getAlbumTracks(albumId: string): Promise<any> {
//TODO: Test this
return new Promise(async (resolve, reject) => {
try{
let albumData: any = {} // {album: {title: , author:, cover: }, tracks: [{title: , audio: }]}
const albumDocument = await this.albumModel.findById(albumId)
console.log('albumDocument :', albumDocument)
const author = await this.userModel.findById(albumDocument.authorId)
const albumTracks = await this.trackModel.find({album: albumDocument._id})
albumData.tracks = albumTracks.map(track => {
return {title: track.title, audio: track.trackUrl, isPremium: track.isPremium}
})
albumData.album = {title: albumDocument.title, author: author.username, cover: albumDocument.coverUrl}
resolve(albumData)
} catch(err) {
reject({code: 500, msg: err.message || err.msg})
}
})
}
【问题讨论】:
-
在需要 mongoose 之后添加这一行。 mongoose.set('debug', true);这将打印下一行触发的实际 mongo 查询。常量专辑文档 = 等待 this.albumModel.findById(albumId);共享被触发的查询。它将有助于调试。