猫鼬findById返回null,并且该ID作为对象ID存储在db

时间:2020-07-29 13:38:35

标签: node.js mongodb mongoose

这是我的架构,我没有定义_id字段,所以它是由猫鼬创建的,其类型是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})
      }
    })
  }

1 个答案:

答案 0 :(得分:-1)

您需要通过将输入ID(作为字符串)解析为ObjectId函数的参数,将其转换为ObjectID。 这是一个猫鼬的样品。

    var mongoose = require('mongoose'); 
    var id = mongoose.Types.ObjectId(stringId);

然后您可以继续在id中使用findById(id)