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

How to reference another schema in one schema using mongoose?

1个答案

1

In Mongoose, if you want to reference another schema within a schema, the common approach is to use an ObjectId field to establish relationships between documents. This is typically achieved by utilizing the Schema.Types.ObjectId data type alongside the ref property, where the ref property specifies the model that can be referenced via ObjectId.

For example, suppose we have two Mongoose models: User and Post. Each Post should be associated with a single User. To establish this relationship, we can create a field in the Post schema that references the ObjectId of the User schema.

Here is an example of how to set up this relationship:

javascript
const mongoose = require('mongoose'); const { Schema } = mongoose; // User schema const userSchema = new Schema({ username: String, email: String // Other fields }); const User = mongoose.model('User', userSchema); // Post schema const postSchema = new Schema({ title: String, content: String, author: { type: Schema.Types.ObjectId, ref: 'User' // Here, 'User' denotes the name of the User model } // Other fields }); const Post = mongoose.model('Post', postSchema); // When creating a Post document and associating it with a User const post = new Post({ title: 'Mongoose Guide', content: 'How to use schemas in Mongoose...', author: someUserId // Assuming this is an existing User's ObjectId }); // Save the Post document post.save(function(err) { if (err) return handleError(err); // Post document saved successfully }); // Later, we can use the populate method to automatically populate the author field Post.findById(postId) .populate('author') // This automatically populates the author field, replacing the ObjectId with the actual User document content .exec(function(err, post) { if (err) return handleError(err); console.log(post.author.username); // Prints the username of the associated User });

In this example, we first define two simple schemas: userSchema and postSchema. Within the postSchema, we add a field named author with type Schema.Types.ObjectId, which specifies the User model via the ref property. When querying Post documents, we can use the populate method to replace the ObjectId of the author field with the corresponding User document.

2024年6月29日 12:07 回复

你的答案