【Node.js工程师养成计划】之使用Node连接MongoDB进行增删改查

发布于:2024-05-13 ⋅ 阅读:(120) ⋅ 点赞:(0)

一、Node连接MongoDB

mongodb

npm install mongodb
# or ...
yarn add mongodb

demo:

const { MongoClient } = require('mongodb');
// or as an es module:
// import { MongoClient } from 'mongodb'

// Connection URL
const url = 'mongodb://localhost:27017';
const client = new MongoClient(url);

// Database Name
const dbName = 'myProject';

async function main() {
  // Use connect method to connect to the server
  await client.connect();
  console.log('Connected successfully to server');
  const db = client.db(dbName);
  const collection = db.collection('documents');

  // the following code examples can be pasted here...

  return 'done.';
}

main()
  .then(console.log)
  .catch(console.error)
  .finally(() => client.close());

在这里插入图片描述

const { MongoClient} = require('mongodb')

const url = 'mongodb://127.0.0.1:27017'
const client = new MongoClient(url)

const dbName = 'test';

async function main() {
  await client.connect();
  console.log('Connected successfully to server')
  const db = client.db(dbName)
  const user = db.collection('user')
  const d = await user.find()
  console.log(await d.toArray())
}

main()
  .then(console.log)
  .catch(console.error)
  .finally(() => client.close())

在这里插入图片描述

在这里插入图片描述

二、使用Node进行增删改查

const { MongoClient} = require('mongodb')

const url = 'mongodb://127.0.0.1:27017'
const client = new MongoClient(url)

const clientFun = async function(c){
  await client.connect()
  console.log('连接成功')
  const db = client.db('test')
  return db.collection(c)
}

async function main() {
  const user = await clientFun('user')
  const d = await user.find()
  console.log(await d.toArray())
}

main()
  .then(console.log)
  .catch(console.error)
  .finally(() => client.close())
const { MongoClient} = require('mongodb')

const url = 'mongodb://127.0.0.1:27017'
const client = new MongoClient(url)

const clientFun = async function(c){
  await client.connect()
  console.log('连接成功')
  const db = client.db('test')
  return db.collection(c)
}

async function main() {
  const user = await clientFun('user')

  // 查询
  // const d = await user.find()
  // const d = await user.findOne({age: {$gt: 18}})
  // const d = await user.find({age: {$gt: 18}})
  // console.log(await d.toArray())

  // 插入
  // const d = await user.insertOne({name: 'aa', age: 6})
  // const d = await user.insertMany([
  //   {name: 'bb', age: 11},
  //   {name: 'cc', age:22}
  // ])
  // console.log(d)

  // 更新
  // const d = await user.updateOne({name: 'Alen111'}, {$set: {name: 'dd'}})
  // console.log(d)

  // 删除
  const d = await user.deleteOne({name: 'Alen1'})
  console.log(d)
}

main()
  .then(console.log)
  .catch(console.error)
  .finally(() => client.close())

网站公告

今日签到

点亮在社区的每一天
去签到