gpt4 book ai didi

node.js - 如何在 Mongoose 中设置数据库名称和集合名称?

转载 作者:行者123 更新时间:2023-12-04 16:27:10 28 4
gpt4 key购买 nike

我正在构建一个连接到 MongoDB-Atlas 的小程序。
我创建了一个连接、一个架构、一个模型并创建了一个文档。
但不知何故,我的数据库名称是“test”,集合名称是“users”,而我没有在代码或 Atlas 中定义它,这是默认名称吗?以及如何创建/重命名数据库和集合。
编码 :
user.js

const mongoose = require('mongoose');
const SchemaObj = mongoose.Schema;
const userSchema = new SchemaObj({
name : {
type:String,
require:true

},
email : {
type:String,
require:true
},
password: {
type:String,
require:true
}
});

mongoose.model('User',userSchema);
app.js
const express = require('express');
const app = express();
const rout = express.Router();
const PORT = 8888;
const {connectionString} = require('./Keys');
const mongoose = require('mongoose');

app.use(express.json());
app.use(require('./routes/auth'));

app.get('/',(req,res)=>{
console.log('succesfully connected');
res.send('im in!');
});

let server = app.listen(PORT,'0.0.0.0',()=>{
let FuncPort = server.address().port
let host = server.address().address
console.log("Example app listening at http://%s:%s", host, FuncPort)
});

const client = mongoose.connect(connectionString, {
useNewUrlParser: true,
useUnifiedTopology: true
});

mongoose.connection.on('connected',()=>{
console.log('connected to mongodb oh hell yea');
});

mongoose.connection.on('error',()=>{
console.log('error connecting to mongodb oh hell yea');
});
auth.js
const mongoose = require('mongoose');
const express = require('express');
const route = express.Router();
require('../moduls/User');
const user = mongoose.model("User");

rout.post('/sign',(req,res)=>{
const {name,password,email} = req.body;
if(name && password && email) {
console.log('you god damn right!');
res.json("you god damn right in response");
} else {
console.log('you are god damn wrong stupid idiot!');
res.status(422);
res.json("you are god damn wrong you stupid idiot in response");
}

user.findOne({email:email}).then((resolve,reject)=>{
if(resolve)
return res.status(422).json("user already exist yo");

const newUser = new user({ name, email, password });
newUser.save().then(() => {
res.json('saved user!!!!');
}).catch(err => {
console.log("there was a problem saving the user")});
}).catch(err => {
console.log(err);
})
});
module.exports = route;
对了, mongoose 有什么区别和 MongoDB图书馆?

最佳答案

为了命名你的 mongodb 数据库,你应该把它放在你的连接字符串中,比如:

mongoose.connect('mongodb://localhost/myDatabaseName');

要命名您的集合或禁用复数,您可以在此处找到答案:

What are Mongoose (Nodejs) pluralization rules?
var schemaObj = new mongoose.Schema(
{
fields:Schema.Type
}, { collection: 'collection_name'});

Mongoose 是用于 MongoDB 和 Node.js 的对象数据建模 (ODM) 库。类似于 Sequelize (ORM),但用于文档 (NoSQL)。

关于node.js - 如何在 Mongoose 中设置数据库名称和集合名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61388479/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com