mongoose的操作
var mongoose = require('mongoose');
//var db = mongoose.connect("mongodb://user:pass@localhost:port/database");
var db = mongoose.connect("mongodb://localhost:27017/test");
db.connection.on("error",function(error){console.log("数据库链接失败:" + error);});
db.connection.on("open",function(){console.log("数据库链接成功!");});
var TestSchema = new mongoose.Schema({
name:{type:String},
age:{type:Number,default:0},
email:{type:String,default:''},
time:{type:Date,default:Date.now}
});
var TestModel = db.model("test1",TestSchema);
var TestEntity = new TestModel({
name:"helloworld",
age:18,
email:"helloworld@qq.com"
});
TestEntity.save(function(error,doc){
if(error){
console.log("error:" + error);
}
else{
console.log(doc);
}
});
//Model保存方法
// Model提供了一个create方法来对数据进行保存。下面我们来看一下示例:
//
// 1. Model.create(文档数据, callback))
Model.find({},function(error,docs){
//若没有向find传递参数,默认的是显示所有文档
});
Model.find({ "age": 28 }, function (error, docs) {
if(error){
console.log("error :" + error);
}else{
console.log(docs); //docs: age为28的所有文档
}
});
TestModel.find({}, function(error, docs) {
console.log(docs);
});
Model.create({ name:"model_create", age:26}, function(error,doc){
if(error) {
console.log(error);
} else {
console.log(doc);
}
});
// entity保存方法
// 刚刚学习了model的create方法,那接下来就开始学习基于entity的保存方法吧。如下示例:
//
// 1. Entity.save(文档数据, callback))
var Entity = new Model({name:"entity_save",age: 27});
Entity.save(function(error,doc) {
if(error) {
console.log(error);
} else {
console.log(doc);
}
});
// model调用的是create方法,entity调用的是save方法,记住了嘛!
// 参考示例,用save方法为集合“test1”添加一条数据(包含属性name、age、email),并console输出返回值?
var TestEntity = new TestModel({
name : "jerry",
age : 28,
email: "jerry@qq.com"
});
TestEntity.save(function(error,doc) {
console.log(doc);
});
// 数据更新
// 学习了数据的保存,接下来我们就开始学习对数据的更新吧!
//
// 1.示例:obj.update(查询条件,更新对象,callback);
var conditions = {name : 'test_update'};
var update = {$set : { age : 16 }};
TestModel.update(conditions, update, function(error){
if(error) {
console.log(error);
} else {
console.log('Update success!');
}
});
// 更新后find一下,此时数据已经修改成功了!
// 删除数据
// 有了数据的保存、更新,就差删除了,下面我们就来学习它吧!
//
// 1.示例:obj.remove(查询条件,callback);
var conditions = { name: 'tom' };
TestModel.remove(conditions, function(error){
if(error) {
console.log(error);
} else {
console.log('Delete success!');
}
});
// 本章节我们讲述了针对数据库的几个操作方法,通过调用相关方法来对数据进行改变,不管是新增、删除、修改还是查查询,你都可以办到。
//
// 简单回顾:
//
// 1. 查询:find查询返回符合条件一个、多个或者空数组文档结果。
//
// 2. 保存:model调用create方法,entity调用的save方法。
//
// 3. 更新:obj.update(查询条件,更新对象,callback),根据条件更新相关数据。
//
// 4. 删除:obj.remove(查询条件,callback),根据条件删除相关数据。

浙公网安备 33010602011771号