Nodejs mongoose如何引用外文件中声明的schema

Nodejs mongoose如何引用外文件中声明的schema

例如在a.js文件中声明了一个comment schema作为本文件另一个schema的内嵌文档,在b.js文件中又有一个新的schema,这个schema也要将commet schema作为自己的内嵌文档,该如何引用?求帮助,最好有个示例什么的。确实解决不了这问题,不是伸手党。 = =

2 回复

当然可以!下面是一个关于如何在Node.js中使用Mongoose引用外部文件中声明的Schema的示例。假设我们有两个文件 a.jsb.js,其中 a.js 中定义了一个 Comment Schema,并且 b.js 中需要使用这个 Comment Schema。

a.js

首先,在 a.js 文件中定义 Comment Schema:

// a.js
const mongoose = require('mongoose');

const commentSchema = new mongoose.Schema({
    text: { type: String, required: true },
    author: { type: mongoose.Schema.Types.ObjectId, ref: 'User' }
});

module.exports = commentSchema;

b.js

接下来,在 b.js 文件中引用并使用 Comment Schema:

// b.js
const mongoose = require('mongoose');
const commentSchema = require('./a'); // 引用a.js中的Comment Schema

const postSchema = new mongoose.Schema({
    title: { type: String, required: true },
    content: { type: String, required: true },
    comments: [commentSchema] // 将Comment Schema作为内嵌文档
});

module.exports = mongoose.model('Post', postSchema);

解释

  1. 模块导出

    • a.js 文件中,我们定义了 commentSchema 并将其导出。
    • b.js 文件中,我们通过 require('./a') 来引入 a.js 文件中的 commentSchema
  2. 内嵌文档

    • b.js 文件中,我们将 commentSchema 作为 comments 字段的类型。这样就实现了在一个 Schema 中引用另一个 Schema 的功能。
  3. 引用外部Schema

    • 使用 require 方法可以轻松地在不同的文件之间共享和重用 Schema 定义。

这样,你就可以在多个文件中重复使用同一个 Schema,而无需重复编写相同的代码。希望这个示例对你有所帮助!


在Node.js中使用Mongoose时,你可以通过模块化的方式将Schema定义在一个单独的文件中,并在其他文件中引用这些Schema。假设你有两个文件 a.jsb.js,其中 a.js 定义了一个嵌入式Schema comment,而 b.js 需要引用该Schema作为其自身的嵌入式文档。

示例代码

a.js 文件

// a.js
const mongoose = require('mongoose');
const Schema = mongoose.Schema;

// 定义 comment schema
const commentSchema = new Schema({
    text: String,
    author: { type: Schema.Types.ObjectId, ref: 'User' },
});

module.exports = commentSchema;

b.js 文件

// b.js
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const commentSchema = require('./a'); // 引用 comment schema

const postSchema = new Schema({
    title: String,
    body: String,
    comments: [commentSchema], // 将 comment schema 作为嵌入式文档
});

module.exports = mongoose.model('Post', postSchema);

解释

  1. 定义 Schema: 在 a.js 文件中,我们定义了一个名为 commentSchema 的嵌入式Schema,它包含了两个字段:textauthor(后者是一个引用到 User 模型的 ObjectId)。

  2. 导出 Schema: 使用 module.exports 导出 commentSchema,这样它可以在其他文件中被引用。

  3. 引用 Schema: 在 b.js 文件中,我们首先引入了 mongooseSchema,然后通过 require('./a') 引用了 a.js 中定义的 commentSchema

  4. 创建主 Schema: 在 b.js 中,我们定义了一个名为 postSchema 的Schema,其中包括一个数组字段 comments,类型为 commentSchema,这样就把 commentSchema 当作嵌入式文档。

这种方式使得你的代码更加模块化和易于维护。每个Schema可以独立地进行修改或扩展,而不会影响到其他部分。

回到顶部