概要:安装Mongodb,数据库创建,创建数据库集合增加数据,接入Nuxt安装工具库、配置数据库
安装Mongodb与语法使用
详情参考【菜鸟】Mongodb
创建数据
1、链接数据库
>mongosh --host localhost --port 27017 -u "testuser" -p "passwrord123" --authenticationDatabase "runoob"
Current Mongosh Log ID: 673702de4df19e91d40d818f
Connecting to: mongodb://<credentials>@localhost:27017/?directConnection=true&serverSelectionTimeoutMS=2000&authSource=runoob&appName=mongosh+2.3.3
Using MongoDB: 8.0.3
Using Mongosh: 2.3.3
2、创建数据库
test> use runoob
switched to db runoob
3、创建集合增加数据
runoob> db.createCollection("myNewCollection")
{ ok: 1 }
runoob> show tables
myNewCollection
runoob> db.myCollection.insertOne({name:"alice",age:30})
{
acknowledged: true,
insertedId: ObjectId('673703dd4df19e91d40d8190')
}
接入安装Nuxt
安装工具库、配置
npm i -D mongodb
import { MongoClient } from 'mongodb'
// mongodb://[username:password@]host1[:port1][,...hostN[:portN]][/[defaultauthdb][?options]]
const dbConfig = {
ip: '127.0.0.1', //IP地址
port: '27017', // 端口 默认是27017
dbname: 'runoob', // 数据库名称
name: 'testuser', // 数据库用户名
password: 'passwrord123' // 数据库密码
}
const url = `mongodb://${dbConfig.name}:${dbConfig.password}@${dbConfig.ip}:${dbConfig.port}/${dbConfig.dbname}`;
const mongodb = MongoClient.connect(url);
export default mongodb;
import mongodb from '../connectSQL'
export default defineEventHandler(async (event) => {
const dbtable = (await mongodb).db('runoob').collection('myNewCollection')
// console.log('dbtable==>', dbtable)
// 查询runoob数据库下的myNewCollection合集
let content = await dbtable.find().toArray()
return {
hello: 'world',
content
}
})
<script lang="ts" setup>
const res = await useFetch('/api/test')
console.log('res====>', res)
</script>