How to connect between database collection in mongodb

Viewed 33

I have created a database collection for the author. How can I connect the author database with Course database collection.

const authorSchema = new mongoose.Schema({
  name: String,
  bio: String,
  website: String,
});
const Author = mongoose.model("Author", authorSchema);

const Course = mongoose.model(
  "Course",
  new mongoose.Schema({
    name: String,
    author:
  })
);

1 Answers

There are two ways you can do is using reference or embedding the data on one another

Referencing

const Author = mongoose.model(
  "Author",
  new mongoose.Schema({
    name: String,
    bio: String,
    website: String,
  })
);

const Course = mongoose.model(
  "Course",
  new mongoose.Schema({
    name: String,
    author: {
        //use as reference
      type: mongoose.Schema.Types.ObjectId,
      ref: "Author",
    },
  })
);

Embedding

const authorSchema = new mongoose.Schema({
  name: String,
  bio: String,
  website: String,
});
const Author = mongoose.model("Author", authorSchema);

const Course = mongoose.model(
  "Course",
  new mongoose.Schema({
    name: String,
      //use as embedded data
    author: authorSchema,
  })
);

Related