mongodb==安装prisma连接
官网下载mongodb,解压安装
Download MongoDB Community Server | MongoDB
修改bin/mongod.cfg
# mongod.conf
# for documentation of all options, see:
# http://docs.mongodb.org/manual/reference/configuration-options/
# Where and how to store data.
storage:
dbPath: D:\sf_develop\mongodb\data
# where to write logging data.
systemLog:
destination: file
logAppend: true
path: D:\sf_develop\mongodb\log\mongod.log
# network interfaces
net:
port: 27017
bindIp: 0.0.0.0
#processManagement:
#security:
#operationProfiling:
replication:
replSetName: rs0
#sharding:
## Enterprise-Only Options:
#auditLog:
创建文件夹D:\sf_develop\mongodb\data\db
下载mongosh
MongoDB Shell Download | MongoDB
启动mongdb
mongod --dbpath D:\sf_develop\mongodb\data\db --replSet rs0
启动mongosh连接上刚才的db
执行rs.initiate
可以了。
安装node.js
创建一个node项目
安装依赖
npm install @prisma/client mongodb
npm install --save-dev prisma
npx prisma init
会发现生成了一个配置文件
编写配置文件
demo-prisma\prisma\schema.prisma
// prisma/schema.prisma
generator client {
provider = "prisma-client-js"
}
datasource db {
provider = "mongodb"
url = env("DATABASE_URL")
}
model User {
id String @id @default(auto()) @map("_id") @db.ObjectId
name String
email String @unique
age Int?
createdAt DateTime @default(now())
}
编写.env文件
DATABASE_URL="mongodb://localhost:27017/prisma-demo"
npx prisma init
会自动在依赖包里生成客户端代码
编写测试代码
const {PrismaClient} = require('@prisma/client');
const prisma = new PrismaClient();
async function main() {
// CREATE: 新增用户
const newUser = await prisma.user.create({
data: {
name: "Alice",
email: "alice@example.com",
age: 25,
},
});
console.log("Created user:", newUser);
// READ: 查询用户
const allUsers = await prisma.user.findMany();
console.log("All users:", allUsers);
// UPDATE: 更新用户
const updatedUser = await prisma.user.update({
where: {email: "alice@example.com"},
data: {age: 26},
});
console.log("Updated user:", updatedUser);
// // DELETE: 删除用户
// const deletedUser = await prisma.user.delete({
// where: {email: "alice@example.com"},
// });
console.log("Deleted user:", deletedUser);
}
main()
.catch((e) => {
console.error(e);
process.exit(1);
})
.finally(async () => {
await prisma.$disconnect();
});
查看结果