我有以下猫鼬模式:
export interface MusicInput {
title: string
artist: string
album: string
genre: string
userId?: string // maybe make this mongoose.type.ObjectId
}
export interface MusicDocument extends mongoose.Document, MusicInput {
createdAt: Date
updatedAt: Date
}
const musicSchema = new mongoose.Schema(
{
title: {
type: String,
require: true
},
artist: {
type: String,
require: true
},
album: {
type: String,
require: true
},
genre: {
type: String,
require: true
},
userId: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User',
require: false
}
},
{ timestamps: true }
)
const MusicModel = mongoose.model<MusicDocument>('Music', musicSchema)
export default MusicModel
我想做的是根据music._id搜索音乐。但我已经尝试了一切可能的方法:
MusicModel.findOne({_id: <some_valid_id>})
或MusicModel.findById(<some_valid_id>)
但它总是返回null。这是我目前用来通过 id 查找音乐的代码:
export const findMusic = async (
query: FilterQuery<MusicDocument>,
options: QueryOptions = { lean: true }
) => {
return MusicModel.findOne(query, {}, options)
}
发生什么事了?我一直在网上冲浪,但仍然找不到解决方案。
猫鼬版本 => 8.5.2
检查集合名称:Mongoose 将模型名称复数化以确定集合名称。确保 MongoDB 中的集合名称与模型名称的复数形式匹配。例如,如果您的模型是
Music
,则集合应该是 musics
。您可以通过显式指定集合名称来覆盖此行为:
const MusicModel = mongoose.model<MusicDocument>('Music', musicSchema, 'music');
验证ID格式:确保您查询的_id格式正确。 Mongoose 期望 _id 是 mongoose.Types.ObjectId 的实例。如果您传递字符串,请将其转换为 ObjectId:
const mongoose = require('mongoose');
const id = mongoose.Types.ObjectId('<some_valid_id>');
MusicModel.findById(id).then((doc) => {
console.log(doc);
}).catch((error) => {
console.error(error);
});
export const findMusic = async (
query: FilterQuery<MusicDocument>,
options: QueryOptions = { lean: true }
) => {
try {
const result = await MusicModel.findOne(query, {}, options);
if (!result) {
console.log('No document found with the given query:', query);
}
return result;
} catch (error) {
console.error('Error finding document:', error);
throw error;
}
};