express中使用mongoose连接MongoDB免费版“沙
2023-10-15 本文已影响0人
small_zeo
tip: 这一版不适用于生产环境,因为它没有冗余设计,但非常适合进行开发和原型设计。
如何将 Mongoose 连接到 MongoDB 云端数据库,如何定义模式和模型
https://cloud.mongodb.com/
注册MongoDB 用户
https://account.mongodb.com/account/register?signedOut=true
单击Create

将打开 Cloud Provider,选择Shared免费沙箱方案


将返回到主屏幕。点击刚创建的新数据库可以打开详细信息屏幕。Collections中即可看到当前数据库的数据


安装Mongoose
npm install mongoose -s
安装 Mongoose 会添加所有依赖项,包括 MongoDB 数据库驱动程序,但不会安装 MongoDB 本身。要安装 MongoDB 服务器,可以 点击下载 各操作系统的安装程序在本地安装。也可以使用云端 MongoDB 实例。
express连接到云端MongoDB
// Set up mongoose connection
const mongoose = require("mongoose");
mongoose.set("strictQuery", false);
const dev_db_url =
"mongodb+srv://<你的MongoDB用户名>:<你的MongoDB密码>@clusterexpress.ur8nwvn.mongodb.net/?retryWrites=true&w=majority"
const mongoDB = process.env.MONGODB_URI || dev_db_url;
main().then(res => {
console.log('success', res)
}).catch((err) => console.log(err));
async function main() {
await mongoose.connect(mongoDB);
}
Cmd Line Tools可以查看详细的数据看接入方式

定义和添加模型
// 定义模式
const Schema = mongoose.Schema;
const SomeModelSchema = new Schema({
name: String
});
// 使用模式“编译”模型
const SomeModel = mongoose.model("SomeModel", SomeModelSchema);
// 创建一个 SomeModel 模型的实例
const awesome_instance = new SomeModel({ name: "zeo" });
// 传递回调以保存这个新建的模型实例
awesome_instance.save().then(res => {
console.log('awesome_instance', res)
})
保存新建的SomeModel模型实例后,即可在云端中查看新增的数据
