Mongoose relations add multiple Id to a Schema (many to One)

In Mongoose, you can establish relationships between documents in different collections by adding references to other document IDs in a schema. To add multiple references (i.e., multiple document IDs) to a schema, you can use an array of ObjectId values. Here's how you can do it:

Suppose you have two schemas, Author and Book, and you want to create a relationship where each book can have multiple authors. Here's how you can define this relationship using Mongoose:

Define the Author Schema.

const mongoose = require('mongoose');

const authorSchema = new mongoose.Schema({
  name: String,
  // Other author properties
});

module.exports = mongoose.model('Author', authorSchema);

Define the Book Schema with an array of author references.

const mongoose = require('mongoose');

const bookSchema = new mongoose.Schema({
  title: String,
  authors: [
    {
      type: mongoose.Schema.Types.ObjectId,
      ref: 'Author',
    },
  ],
  // Other book properties
});

module.exports = mongoose.model('Book', bookSchema);

In the bookSchema, the authors field is an array of references to Author documents. The type is set to mongoose.Schema.Types.ObjectId, indicating that it contains ObjectId values. The ref field specifies the target collection, which is 'Author' in this case.

Create and Populate Documents.

You can create and populate documents as follows:

const Author = require('./authorModel'); // Import your Author model
const Book = require('./bookModel'); // Import your Book model

// Create authors
const author1 = new Author({ name: 'Author 1' });
const author2 = new Author({ name: 'Author 2' });

// Save authors to the database
author1.save();
author2.save();

// Create a book with multiple authors
const book = new Book({
  title: 'Book Title',
  authors: [author1._id, author2._id], // Add author IDs to the book's authors array
});

// Save the book to the database
book.save();

In this example, we first create two Author documents and save them to the database. Then, we create a Book document and populate its authors array with the IDs of the authors we created earlier.

Now, you have established a relationship where a book can have multiple authors, and you can easily populate the authors details when querying a book document using Mongoose's populate method.

Muhammad Alfaiz
Alfaiz 6 months ago
Subscribe
Notify of
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x