databasemongodbmongoosemern

How Connect to multiple collections in Mongoose?


I want to store books in a collection called books and users in a collection called users, but I don’t know how to do this in Mongoose.JS

config/db.js:

import mongoose from "mongoose"

export const connectDB = async () => {
    try {
        const conn = await mongoose.connect(process.env.MONGO_URI);
        console.log(`MongoDB Connected: ${conn.connection.host}`)
    }
    catch(err){
        console.error(err);
        process.exit(1);
    }
    

book.model.js:

import mongoose from "mongoose";


const bookSchema = new mongoose.Schema({
    title: {
        type: String,
        required: true
    },
    author :{
        type: String,
        required: true
    },
    descripton :{
        type: String,
    },
    price: {
        type: Number,
        required: true
    },
    cover: {
        type: String,
        required: true
    },
    amount:{
        type: Number,
    },
    publishedDate: {
        type: Date,
        required: false
    },
    genre: {
        type: String,
        required: false
    },
    isbn: {
        type: String,
        required: true,
        unique: true
    },
    status: {
        type: String,
        enum: ['Available', 'Out of Stock', 'Pre-order'],
        default: 'Available'
    },
    tags: [String]

}, { timestamps: true });

const Book = mongoose.model("Book", bookSchema);

export default Book;

users.model.js:

import mongoose from 'mongoose';


const UserSchema = new mongoose.Schema({
    username: {
        type: String,
        required: [true, 'Username is required'],
        unique: true,
    },
    email: {
        type: String,
        required: [true, 'Email is required'],
        unique: true,
    },
    passowrd : {
     type: String,
     required: [true, 'Password is required'],
    },
    role : {
     type: String,
     enum: ['Admin','User'],
     default: 'User'
    }
    
})


const User = mongoose.model('User', UserSchema);

export default User; 

**
server.js:**

import express from 'express';
import dotenv from 'dotenv';
import {connectDB} from './config/db.js';
import bookRoutes from './routes/book.route.js';
import cors from 'cors';
import bodyParser from 'body-parser';

dotenv.config();
const PORT = process.env.PORT || 5000;
const app = express();
/* Middlewares */
app.use(express.json());
app.use(cors());
app.use(bodyParser.json());

/* ================ */ 



app.use("/api/books", bookRoutes)

app.listen(PORT,()=>{
    try {
        connectDB();
        console.log(`Server Start at port 5000 check : http://localhost:${PORT}`);
    } catch (err){
        console.log(err.message);
    }
   
})

.env :

MONGO_URI = mongodb+srv://XXX:XXXX@cluster0.o2axi.mongodb.net/books?retryWrites=true&w=majority&appName=Cluster0

PORT = 5000

What should I do next to store users in the users collection? I want to build an Auth system that is why i need to build another collection. any suggestions? or guide? Thank you in advance


Solution

  • Just simply add another user field in the bookSchema:

    ...
    user: {
        type: mongoose.Schema.Types.ObjectId,
        ref: "User"
    },
    ...