作者:ab15b7k1_198 | 来源:互联网 | 2024-09-28 19:59
篇首语:本文由编程笔记#小编为大家整理,主要介绍了MongoDB快速入门教程 (4.1)相关的知识,希望对你有一定的参考价值。
4.Mongoose使用
4.1.nodejs操作mongodb
文档地址:http://mongodb.github.io/node-mongodb-native/3.2/tutorials/crud/
1.安装mongodb驱动
npm install mongodb --save-dev
2.连接数据库
const MOngoClient= require('mongodb').MongoClient;
var dburl = "mongodb://admin:123456@127.0.0.1:27017";
MongoClient.connect(dburl, {useNewUrlParser:true}, (err,client)=>{
if(err){
console.log('数据库连接失败!');
return;
};
const db = client.db("test")
});
3.插入数据
const MOngoClient= require('mongodb').MongoClient;
var url = "mongodb://admin:123456@127.0.0.1:27017";
var client = new MongoClient(url)
client.connect((err,client)=>{
if(err){
console.log('数据库连接失败!');
return;
};
const db = client.db("test")
// 插入数据
db.collection("user").insertOne({"name": "nodeing", "age": 18}, (err, result) => {
console.log(result)
})
});
4.更新数据
const MOngoClient= require('mongodb').MongoClient;
var url = "mongodb://admin:123456@127.0.0.1:27017";
var client = new MongoClient(url)
client.connect((err,client)=>{
if(err){
console.log('数据库连接失败!');
return;
};
const db = client.db("test")
db.collection('user').updateOne({"name": "nodeing"}, {$set: {"age": 38}}, (err, result)=>{
console.log(result)
client.close();
})
});
5.删除数据
const MOngoClient= require('mongodb').MongoClient;
var url = "mongodb://admin:123456@127.0.0.1:27017";
var client = new MongoClient(url)
client.connect((err,client)=>{
if(err){
console.log('数据库连接失败!');
return;
};
const db = client.db("test")
db.collection('user').deleteOne({"name": "nodeing"}, (err, result)=>{
console.log(result)
client.close();
})
});
螺钉课堂视频课程地址:http://edu.nodeing.com