node[19]-mongoose操作mongoDB数据库

mongoose

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
var mongoose = require('mongoose');

mongoose.Promise = global.Promise;

mongoose.connect('mongodb://localhost:27017/TodoApp');

//建立模型
var Todo = mongoose.model('Todo',{
text:{
type:String
},
completed:{
type:Boolean
},
completedAt:{
type:Number
}
});

//存储
var newTodo = new Todo({
text:'Cook dinner'
});

newTodo.save().then((doc)=>{
console.log('Save todo',doc);
},(e)=>{
console.log('Unable to save todo');
});

mongoose validators

下面的程序失败,因为text去空格后的值的长度小于1:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
var mongoose = require('mongoose');

mongoose.Promise = global.Promise;

mongoose.connect('mongodb://localhost:27017/TodoApp');


var Todo = mongoose.model('Todo',{
text:{
type:String, //类型
required:true, //必须要有
minlength:1, //最小长度
trim:true //去除空格
},
completed:{
type:Boolean,
default:false //默认值
},
completedAt:{
type:Number,
default:null
}
});
//失败,因为text去空格后的值的长度小于1。
var newTodo = new Todo({
text:' ',

});

newTodo.save().then((doc)=>{
console.log('Save todo',doc);
},(e)=>{
console.log('Unable to save todo');
});