Mongoose benefits
- You can create a model structure (Schema) for the document can be verified on the model of the object / document
- It can be converted to data type conversion object model
- You can use middleware to application business logic hooks
- Native MongoDB easier than driving Node
The new object is provided Mongoose
- Schema (Object Model) object defines the constraint in the document structure of the database
- Model object as represented by all the documents in the collection, corresponds to a set of database MongoDB Collection
- the Document indicates a particular document collection, corresponds to a set of specific documentation
Download and install
npm i mongoose --save
Basic Usage
//引入
var mongoose = require("mongoose");
//连接数据库
mongoose.connect("mongodb://127.0.0.1/mongoose_test" , { useNewUrlParser: true, useUnifiedTopology:true});
mongoose.connection.once("open",function(){
console.log("--> 数据库连接成功");
});
mongoose.connection.once("close",function(){
console.log("--> 数据库连接已经断开");
});
//断开数据库连接
//mongoose.disconnect();
//将mongoose.Schema 赋值给一个变量
var Schema = mongoose.Schema;
//创建Schema(模式)对象
var stuSchema = new Schema({
name:String,
age:Number,
gender:{
type:String,
default:"female"
},
address:String
});
//通过Schema来创建Model
//Model代表的是数据库中的集合,通过Model才能对数据库进行操作
//mongoose.model(modelName, schema):
//modelName 就是要映射的集合名 mongoose会自动将集合名变成复数
var StuModel = mongoose.model("student" , stuSchema);
/*
- 有了Model,我们就可以来对数据库进行增删改查的操作了
Model.create(doc(s), [callback])
- 用来创建一个或多个文档并添加到数据库中
- 参数:
doc(s) 可以是一个文档对象,也可以是一个文档对象的数组
callback 当操作完成以后调用的回调函数
查询的:
Model.find(conditions, [projection], [options], [callback])
- 查询所有符合条件的文档 总会返回一个数组
Model.findById(id, [projection], [options], [callback])
- 根据文档的id属性查询文档
Model.findOne([conditions], [projection], [options], [callback])
- 查询符合条件的第一个文档 总和返回一个具体的文档对象
conditions 查询的条件
projection 投影 需要获取到的字段
- 两种方式
{name:1,_id:0}
"name -_id"
options 查询选项(skip limit)
{skip:3 , limit:1}
callback 回调函数,查询结果会通过回调函数返回
回调函数必须传,如果不传回调函数,压根不会查询
*/
//增:StuModel.create(doc, function(err){});
StuModel.create({
name:"张三",
age:16,
address:"北京"
},function (err) {
if(!err){
console.log("插入成功");
}
});
//查
StuModel.find({},"name age -_id", {skip:3 , limit:1} , function (err , docs) {
if(!err){
console.log(docs);
}
});
/*
修改
Model.update(conditions, doc, [options], [callback])
Model.updateMany(conditions, doc, [options], [callback])
Model.updateOne(conditions, doc, [options], [callback])
- 用来修改一个或多个文档
- 参数:
conditions 查询条件
doc 修改后的对象
options 配置参数
callback 回调函数
Model.replaceOne(conditions, doc, [options], [callback])
* */
StuModel.updateOne({name:"张三"},{$set:{age:20}},function (err) {
if(!err){
console.log("修改成功");
}
});
/*
删除:
Model.remove(conditions, [callback])
Model.deleteOne(conditions, [callback])
Model.deleteMany(conditions, [callback])
*/
StuModel.remove({name:"李四"},function (err) {
if(!err){
console.log("删除成功");
}
});
/*
Model.count(conditions, [callback])
- 统计文档的数量的
*/
StuModel.count({},function (err , count) {
if(!err){
console.log(count);
}
});
//创建一个Document
var stu = new StuModel({
name:"奔波霸",
age:48,
gender:"male",
address:"碧波潭"
});
stu.save(function (err) {
if(!err){
console.log("保存成功~~~");
}
});
StuModel.findOne({},function (err , doc) {
if(!err){
/*
update(update,[options],[callback])
- 修改对象
remove([callback])
- 删除对象
*/
//console.log(doc);
/*doc.update({$set:{age:28}},function (err) {
if(!err){
console.log("修改成功~~~");
}
});*/
/*doc.age = 18;
doc.save();*/
/*doc.remove(function (err) {
if(!err){
console.log("大师兄再见~~~");
}
});*/
/*
get(name)
- 获取文档中的指定属性值
set(name , value)
- 设置文档的指定的属性值
id
- 获取文档的_id属性值
toJSON() ******
- 转换为一个JSON对象
toObject()
- 将Document对象转换为一个普通的JS对象
转换为普通的js对象以后,注意所有的Document对象的方法或属性都不能使用了
*/
//console.log(doc.get("age"));
//console.log(doc.age);
//doc.set("name","猪小小");
//doc.name = "hahaha";
//console.log(doc._id);
//var j = doc.toJSON();
//console.log(j);
//var o = doc.toObject();
//console.log(o);
doc = doc.toObject();
delete doc.address;
console.log(doc._id);
}
});
Creating Schema Schema objects
var userSchema = new Schema(definition, option);
- options commonly used options
• autoIndex Boolean value that open automatically indexed, default to true
• bufferCommands Boolean value, the cache because the statement connectivity issues can not be executed, default to true
• capped set the maximum number of documents
• collection specified Schema name of the collection application
• id boolean is there _id applied to the processor id, default true
• _id Boolean value, whether to automatically assign an id field, default true
• strict Boolean value that does not meet the Schema object is not inserted into the database, default true
- Schema schema object definitions
- Mode fields and field definitions for the document type in the set.
- For each field mode, you need to set a particular value class
type. Supported types are as follows:- String
- Number
- Boolean
- Array
- Buffer
- Date
- ObjectId or Oid
- Mixed
- You need to define a model for each different document types
Create a model object Model
- Model (name, [Schema], [Collection], [skipInit])
• Parameter name corresponds to the name of the model, the model can be found later with too name.
• schema is to create a good model object.
• collection is the collection name to connect.
• skipInit whether to skip initialization, the default is false
- The method of the object model
- remove(conditions, callback)
- deleteOne(conditions, callback)
- deleteMany(conditions, callback)
- find(conditions, projection, options, callback)
- findById(id, projection, options, callback)
- findOne(conditions, projection, options, callback)
- count(conditions, callback)
- create(doc, callback)
- update(conditions, doc, options, callback)
- ...
Creating Document Document Object
- The method of the document object
- equals(doc)
- id
- get(path,[type])
- set(path,value,[type])
- update(update,[options],[callback])
- save([callback])
- remove([callback])
- isNew
- isInit(path)
- toJSON ()
- toObject()
- ...