我正在尝试从 MongoDB 集合中获取文档。在数据库中,我有这个文档:
我面临的问题是我无法获取内容数组。在获取的文档中,根本没有这个字段。请指导我我在这里犯了什么错误?
这是我的架构:
import { Schema, model, models } from "mongoose";
const ContentSchema = new Schema(
{
_id: {
type: Schema.Types.ObjectId,
required: true,
},
type: {
type: String,
required: true,
},
},
{ _id: false },
);
const BlogSchema = new Schema(
{
_id: {
type: Schema.Types.ObjectId,
required: true,
},
createdAt: {
type: Date,
default: Date.now,
required: true,
},
heading: {
type: String,
required: true,
},
paragraph: {
type: String,
required: true,
},
coverImagePath: {
type: String,
required: true,
},
content: {
type: [ContentSchema],
required: true,
},
},
{ timestamps: true },
);
const BlogModel = models.blog || model("blog", BlogSchema);
export default BlogModel;
这就是我从该集合中获取所有文档的方式,(目前,该集合中只有 1 个我手动创建的文档。)
const blogsCollectionData = (await BlogModel.find({})) as BlogDocType[];
这是博客文档类型:
export type BlogDocType = {
_id: ObjectId;
createdAt: Date;
paragraph: string;
heading: string;
coverImgPath: string;
content: BlogContentDoc[];
};
export type BlogContentDoc = {
type: string;
_id: ObjectId;
};
但是当我打印文档时,这就是我得到的:
[
{
createdAt: 1725884791793,
_id: new ObjectId('66dbba46cd201551710e0499'),
heading: 'Some of my data',
coverImagePath: 'public/blogImages/001.png',
createdAT: 2000-12-31T19:00:00.000Z,
paragraph: 'This is a test paragraph'
}
]
我尝试将架构与数据库文档完全匹配,但我无法弄清楚为什么它不获取内容数组。我还审查了双方的数据类型以确保它们匹配,但仍然不是所需的结果。
不确定是否是这种情况,但我一直在努力解决同样的问题,解决方案是使用嵌入而不是引用。
import mongoose from "mongoose";
//instead of using the Model use the schema here
import {queueSchema} from "./QueueModel";
const tournamentSchema = new mongoose.Schema(
{
name: {type: String, required: true},
categories: [{type: String, required: true}],
description: {type: String},
//found that this is called embedding
queues: [queueSchema]
// queues: [{type: mongoose.Schema.Types.ObjectId, ref: "QueueModel"}]
},
{collection: "tournaments"}
)