【问题标题】:mongoose findById returns null and the id was stored as an object id in the dbmongoose findById 返回 null 并且 id 作为对象 id 存储在数据库中
【发布时间】: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);共享被触发的查询。它将有助于调试。

标签: node.js mongodb mongoose


【解决方案1】:

您需要将输入 id(字符串)转换为 ObjectID,方法是将其作为 ObjectId 函数的参数进行解析。 这是一个带有猫鼬的示例。

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-06-24
    • 2014-10-29
    • 1970-01-01
    • 2018-05-29
    • 2016-04-19
    • 2017-01-01
    • 2020-09-09
    • 2017-10-10
    相关资源
    最近更新 更多