如何在 Mongoose 中连接到多个集合?

问题描述 投票:0回答:1

我想将 books 存储在名为 books 的集合中,将用户存储在名为 users 的集合中,但我不知道如何在 Mongoose.JS 中执行此操作

配置/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; 

**
服务器.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:[电子邮件受保护]/books?retryWrites=true&w=majority&appName=Cluster0

端口 = 5000

接下来我应该做什么才能将用户存储在 users 集合中?我想构建一个身份验证系统,这就是为什么我需要构建另一个集合。有什么建议吗?或指导? 提前谢谢您

database mongodb mongoose mern
1个回答
0
投票

只需在

user
中添加另一个
bookSchema
字段即可:

...
user: {
    type: mongoose.Schema.Types.ObjectId,
    ref: "User"
},
...
© www.soinside.com 2019 - 2024. All rights reserved.