我想将书籍存储在名为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;
用户.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);
}
})
.环境变量:
MONGO_URI = mongodb+srv://XXX: [email protected] /books?retryWrites=true&w=majority&appName=Cluster0
端口 = 5000
我接下来应该怎么做才能将用户存储在用户集合中?我想构建一个 Auth 系统,这就是我需要构建另一个集合的原因。有什么建议吗?或指南?提前谢谢