1.关于Mongoose
1.Mongoose支持的数据类型 String -- 字符串 Number -- 数字,包括整数和小数 Date -- 日期 Boolean -- 布尔 Buffer -- 用于存储二进制数据,eg:图片,最大不超过16M ObjectId -- mongodb自动生成_id,作为数据库的主键 Mixed -- 可以存储任意的数据类型 Array -- 数组或内置子文档(subdocuments) 说明: Array类型的两种用法: 1.array数组数据 eg: var UserSchema = new mongoose.Schema({ name:String , email:[String] }); 2.内置subdocuments eg: var EmailSchema = new mongoose.Schema({ email:String, regTime: Date }); var UserSchema = new mongoose.Schema({ name:String, email:[emailSchema] }); 3.Mongoose的用法 eg: 1.定义Schema结构 var UserSchema = new mongoose.Schema({ name:{type:String ,unique:true, index:true} , email:{type:String , unique:true} , regTime:{type:Date , default:Date.now } , modifiedTime: Date, lastLogin: Date }); 2.Model --- 与MongoDB的document一一对应 schema打包成model,model会自动生成所有的 增(save)、删(delete)、改(update)、查(find,findOne,findById) 方法 生成一个Model mongoose.model('User',UserSchema) eg: 查询年龄在21~65岁之间的User var User = require('./user'); User.find({age:{$gte:21, $lte:65}},callback); <=等价于=> User.where('age').gte(21).lte(65).exec(callback);
2.Mongoose进行CRUD操作
Model methods and instance methods
So what do we mean by model methods? Well, if we have a model called User, some of the methods provided by Mongoose are User.create, User.find, User.update, and User.remove. The method names may be slightly different, but out of the box we’ve got methods for all four CRUD (Create, Read, Update, and Delete) operations right there.
Creation
– Adding data to the instance
var newUser = new User({ name: 'Simon Holmes', email: 'simon@theholmesoffice.com', lastLogin : Date.now() });
– Saving an instance
newUser.save( function( err ){ if(!err){ console.log('User saved!'); } });
– Using the saved data
newUser.save( function( err, user ){ if(!err){ console.log('Saved user name: ' + user.name); console.log('_id of saved user: ' + user._id); } });
Querying
There are a number of static model methods provided by Mongoose to assist in the bulk of find operations, including
– Model.find
– Model.findOne
– Model.findById
User.find({'name' : 'Simon Holmes'}) .where('age').gt(18) .sort('-lastLogin') .select('_id name email') .exec(function (err, users){ if (!err){ console.log(users); // output array of users found } });
Model.findOne
User.findOne({'name' : 'Simon Holmes'}) .where('age').gt(18) .sort('-lastLogin') .select('_id name email') .exec(function (err, users){ if (!err){ console.log(users); // output array of users found } });
Model.fin