Nodejs操作mongodb

Nodejs操作mongodb

使用该命令安装mongodb

npm install mongodb
const { MongoClient } = require('mongodb')
const client = new MongoClient('mongodb://127.0.0.1:27017')
const main = async () => {
  await client.connect()
  const db = client.db('mytest')
  const cc = db.collection('cc')
  const d = await cc.find()
  console.log(await d.toArray())
}
main().finally(() => client.close())

将以上代码优化

// nodejs链接mongodb
const { MongoClient } = require('mongodb')
const client = new MongoClient('mongodb://127.0.0.1:27017')
//封装一个函数 
const clientFun = async function (c) {
  await client.connect()
  const db = client.db('mytest')
  return db.collection(c)
}
const main = async () => {
  let cc = await clientFun('cc')
  let d = await cc.find() //查询
  console.log(await d.toArray()) //默认返回的是游标 需要toArray方法转换
  //增加一条
  let addOne = await cc.insertOne({ usename: 'moncias', age: 30 })
  //增加多条数据
  let addMore = await cc.insertMany([
    { usename: 'moncias', age: 30 },
    { usename: 'moncia1', age: 40 },
    { usename: 'moncia2', age: 41 },
    { usename: 'moncia3', age: 42 }
  ])
  //条件查询 查询一条
  const filter = await cc.findOne({ age: { $gt: 15 } })
  //条件查询多条
  const filters = await cc.find({ age: { $gt: 15 } })
  // 根据条件更新一条
  const updateOne = await cc.updateOne({ age: { $gt: 15 } }, { $set: { usename: 'ws' } })
  //根据条件更新多条
  const updateMany = await cc.updateOne({ age: { $gt: 15 } }, { $set: { usename: 'ms' } })
  //根据条件删除一条
  const deleteOne = await cc.deleteOne({ age: { $gt: 10 } })
   //根据条件删除多条
  const deleteMore = await cc.deleteMany({ age: { $gt: 40 } })
}
main().finally(() => client.close())
Node.js提供了许多不同的方式来操作MongoDB数据库。以下是其中一些常见的方法: 1.使用官方的MongoDB Node.js驱动程序 可以使用官方的MongoDB Node.js驱动程序来连接和操作MongoDB数据库。这个驱动程序提供了许多不同的方法和选项,可以满足不同的需求。以下是一个简单的例子,展示如何使用官方驱动程序连接到MongoDB数据库,并执行简单的查询操作: ``` const MongoClient = require('mongodb').MongoClient; // Connection URL const url = 'mongodb://localhost:27017'; // Database Name const dbName = 'myproject'; // Use connect method to connect to the server MongoClient.connect(url, function(err, client) { console.log("Connected successfully to server"); const db = client.db(dbName); // Find some documents db.collection('users').find({}).toArray(function(err, docs) { console.log("Found the following records"); console.log(docs); client.close(); }); }); ``` 2.使用Mongoose库 Mongoose是一个MongoDB对象模型工具,它提供了一种更简单的方式来操作MongoDB数据库。它允许您定义模式和模型,以便更轻松地执行常见的操作,如插入、更新和查询文档。以下是一个例子,展示如何使用Mongoose连接到MongoDB数据库,并定义一个简单的用户模型: ``` const mongoose = require('mongoose'); // Connection URL const url = 'mongodb://localhost:27017/myproject'; // Connect to the database mongoose.connect(url, {useNewUrlParser: true}); // Define a schema const userSchema = new mongoose.Schema({ name: String, email: String, age: Number }); // Define a model const User = mongoose.model('User', userSchema); // Create a new user const user = new User({ name: 'John Smith', email: 'john@example.com', age: 30 }); // Save the user to the database user.save(function(err) { if (err) throw err; // Find all users User.find(function(err, users) { if (err) throw err; console.log(users); mongoose.connection.close(); }); }); ``` 3.使用第三方库 除了官方驱动程序和Mongoose之外,还有许多其他的Node.js库可以用于操作MongoDB数据库。一些流行的库包括MongoDB Native、mongojs和Monk。这些库提供了不同的API和功能,可以满足不同的需求。以下是一个例子,展示如何使用mongojs库连接到MongoDB数据库,并执行简单的查询操作: ``` const mongojs = require('mongojs'); // Connection URL const url = 'mongodb://localhost:27017/myproject'; // Connect to the database const db = mongojs(url, ['users']); // Find all users db.users.find(function(err, users) { if (err) throw err; console.log(users); db.close(); }); ``` 无论您选择使用哪种方法,Node.js提供了许多选项和库,可以帮助您轻松地操作MongoDB数据库
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值