MongoDB

MongoDB使用集合(collection)和文档(document)来描述和存储数据,collection就相当于表,document相当于行。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
show dbs
use demo
db.dropDatabase()
db.createCollection("user")
show collections
user = db.getCollection("user")
user.insert({name:"cheyenne"})
user.find({name:"cheyenne"})
user.find();//找到全部记录
user.remove({name:"ss"})
user.drop()
//更新集合中的文档
user.save({_id:ObjectId("55cc25b360bcee730bafd2bf"),name:"ZhangSan"})
user.update({name:"ZhangSan"},{name:"ZhangSan",password:"567890"})
user.update({name:"ZhangSan"},{$set: {password:"567890"}});//$set设置字段的值

nodejs有针对MongoDB的数据库驱动:mongodb

Mongoose

创建一个连接

1
2
3
4
5
6
7
8
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test');
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
console.log("we're connected!");
});

在Mongoose中,一切都是从Schema中衍生出来的,schema可以理解为表结构的定义,每个Schema会映射到mongodb的一个collection,它不具备操作数据库的能力。

定义好了Schema,接下来由Schema生成Model。

将Schema编译成Model,Model是一个类,每一条数据都是一个对象,它拥有在Schema中定义的属性和方法,可以对数据库操作。

内置的Promises

Mongoose的异步操作,比如:.save()和查询

为了向后兼容,Mongoose4默认返回一个mpromise。

Mongoose queries不是一个promise对象,但它确实有个.then()方法

mongoose构建在mongodb上,提供了Schema、Model和Document对象,用起来更为方便。

我们可以用Schema对象定义文档的结构(类似表结构),可以定义字段和类型、唯一性、索引和验证。Model对象表示集合中的所有文档。Document对象作为集合中的单个文档的表示。mongoose还有Query和Aggregate对象,Query实现查询,Aggregate实现聚合。

Nodejs连接MongoDB

nodejs连接mongodb时,mongodb://localhost:27011/myproject1连接字符串中最后的表名如果在数据库里不存在会自动创建,如果没有指定数据库则MongoClient使用默认的test数据库

插入数据:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
var insertDocuments = function(db, callback) {
// Get the documents collection
var collection = db.collection('documents');
// Insert some documents
collection.insertMany([
{a : 1}, {a : 2}, {a : 3}
], function(err, result) {
assert.equal(err, null);
assert.equal(3, result.result.n);
assert.equal(3, result.ops.length);
console.log("Inserted 3 documents into the collection");
callback(result);
});
}

insert方法返回了一个对象,有如下三个属性:

  • result Contains the result document from MongoDB
  • ops Contains the documents inserted with added _id fields
  • connection Contains the connection used to perform the insert

nodejs支持所有的MongoDB身份验证机制