Node.js使用MongoDB
MongDB是现在比较流行非关系数据库(NoSQL)。它里面存放的记录称为document,由键(field)值(value)构成,非常类似于JSON数据,而且value值也可以是其它的document。document(?record)构成collection(?table),collection构成数据库。
MongoDB windows和linux安装比较简单,见官网https://docs.mongodb.org/manual/installation/
mongodb.js
安装MongoDB官方驱动mongodb
和调试工具assert
npm install mongodb --save
npm install assert --save
//加载模块
var MongoClient = require('mongodb').MongoClient, assert = require('assert');
// MongoDB地址,数据库mongoExp如果不存在则自动创建
var url = 'mongodb://localhost:27017/mongoExp';
// 连接数据库
MongoClient.connect(url, function(err, db) {
assert.equal(err, null);
console.log("连接成功!");
// 获取集合,如果集合不存在则创建集合
var collection = db.collection("students");
// 插入一条数据
collection.insertOne({
name : "小明",
class : "三年级",
grade : "99"
}, function(err, result) {
assert.equal(err, null);
console.log("插入第一条记录成功");
// 插入第二条数据
collection.insertOne({
name : "张旻",
class : "三年级",
grade : "95"
}, function(err, result) {
assert.equal(err, null);
console.log("插入第二条记录成功");
// 查找集合信息
collection.find({}).toArray(function(err, docs) {
assert.equal(err, null);
console.log("找到:");
console.log(docs);
// 查找一条记录
collection.find({
"name" : "张旻"
}).each(function(err, docs) {
assert.equal(err, null);
if (docs !== null) {
console.log("找到张旻:");
console.log(docs);
}
});
// 修改记录
collection.updateOne({
"name" : "小明"
}, {
$set : {
"name" : "小青"
}
}, function(err, result) {
assert.equal(err, null);
console.log("修改成功!");
});
// 删除记录
collection.deleteMany({
"name" : "张旻"
}, function(err, results) {
assert.equal(err, null);
console.log("删除成功");
collection.find({}).toArray(function(err, docs) {
assert.equal(err, null);
console.log("找到:");
console.log(docs);
// 删除集合
db.dropCollection("students", function(err, result) {
assert.equal(err, null);
console.log("删除成功");
collection.find({}).toArray(function(err, docs) {
assert.equal(err, null);
console.log("找到:");
console.log(docs);
// 关闭数据库
db.close();
});
});
});
});
});
});
});
});
运行
npm mongodb.js
程序中用到的一些操作数据的方法数据的函数
1. 插入一条document db.collection.insertOne({document},callback);
2. 跟新一条document db.collection.updateOne({“name”,”value”},$set{“field”:”value”},callback);
3. 查找document db.collection.find({“field”,”value”}).each(callback);
4. 删除document db.collection.deleteMany({“field”,”value”}).each(callback);
5. 删除collection db.dropCollection(“collectionName”, callback)