乐闻世界logo
搜索文章和话题

How to reference another schema in one schema using mongoose?

4 个月前提问
3 个月前修改
浏览次数11

1个答案

1

在Mongoose中,如果您想在一个schema中引用另一个schema,通常的做法是使用ObjectId字段来创建文档之间的关联。这通常是通过使用Schema.Types.ObjectId数据类型和ref属性来实现的,ref属性指定了可以通过ObjectId引用的模型。

举个例子,假设我们有两个Mongoose模型:一个是User,另一个是Post。每个Post都应该关联到一个User。要实现这种关系,我们可以在Post schema中创建一个字段来引用User schema的ObjectId。

以下是如何设置这种关联的代码示例:

javascript
const mongoose = require('mongoose'); const { Schema } = mongoose; // User schema const userSchema = new Schema({ username: String, email: String // 其他字段 }); const User = mongoose.model('User', userSchema); // Post schema const postSchema = new Schema({ title: String, content: String, author: { type: Schema.Types.ObjectId, ref: 'User' // 这里的 'User' 就是User模型的名称 } // 其他字段 }); const Post = mongoose.model('Post', postSchema); // 使用时,可以像下面这样创建一个Post文档并关联到User const post = new Post({ title: 'Mongoose指南', content: '如何在Mongoose中使用schema引用...', author: someUserId // 假设这是已经存在的User的ObjectId }); // 保存Post文档 post.save(function(err) { if (err) return handleError(err); // Post文档保存成功 }); // 之后我们可以使用populate方法来自动填充author字段 Post.findById(postId) .populate('author') // 这会自动填充author字段,替换ObjectId为User文档的实际内容 .exec(function(err, post) { if (err) return handleError(err); console.log(post.author.username); // 打印出关联User的用户名 });

在这个例子中,我们首先定义了两个简单的schema:userSchemapostSchema。在postSchema中,我们添加了一个名为author的字段,这个字段的类型为Schema.Types.ObjectId,并且我们通过ref属性指定了这个字段应该引用User模型。然后,在查询Post文档时,我们可以用populate方法把author字段的ObjectId替换为对应的User文档。

2024年6月29日 12:07 回复

你的答案