这是我的模式,我没有定义_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})
}
})
}
您需要将输入id(即字符串)转换为ObjectID,方法是将其解析为ObjectID函数的参数。 这是猫鼬的样品。
var mongoose = require('mongoose');
var id = mongoose.Types.ObjectId(stringId);
然后,您可以继续使用FindById(id)
中的id