Mongoose 学习笔记

老是忘记,既然这样,就写篇文章记录下自己常用的用法吧
碰到新的用法,随时保持更新

Schema

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
var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var blogSchema = new Schema({
title: String,
author: String,
body: String,
comments: [{ body: String, date: Date }],
date: { type: Date, default: Date.now },
hidden: Boolean,
votes: Number,
meta: {
createAt: {
type: Date,
default: Date.now()
},
updateAt: {
type: Date,
default: Date.now()
}
}
});

blogSchema.pre('save', function(next) {
if (this.isNew) {
this.meta.creatAt = this.meta.updateAt = Date.now();
} else {
this.meta.updateAt = Date.now();
}
next();
});

module.exports = mongoose.model('Blog', blogSchema);

新建

1
2
3
4
5
6
7
8
9
10
11
var _blog = new Blog({
title: '美好的一天',
author: 'Kieran',
body: '啊!今天真美好~',
});

var promise = _blog.save();

promise.then(function (doc) {
assert.equal(doc.author, 'Kieran');
});

查询 Query

1
2
3
4
5
6
7
8
9
10
11
12
13
14
findById() // 略
findOne() // 略

// find()
var promise = Blog.find({
body: /美好/, // 正则查询
votes: { $gt: 22, $lte: 100 }, // 投票数 大于22 小于等于100
author: { $in: ['Kieran', 'XXX'] }
}).
sort({ date: -1, title: -1 }). // 排序 先按 date 排序, date 一样再按 title 排序
skip(3). // 分页,第三页
limit(10). // 取十条
select('title author body'). // 只取 title author body 字段
exec();

更新 update

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
var query = {};
// 详细的更新操作请看这个 https://docs.mongodb.com/manual/reference/operator/update/
var update = { // update 可同时设置多种类型的更新
$set: { // 普通更新
title: '啦啦啦'
},
$inc: { // 相当于 votes += 2
votes: 2
}
};
/**
Valid options:
safe (boolean) safe mode (defaults to value set in schema (true))
upsert (boolean) whether to create the doc if it doesn't match (false)
multi (boolean) whether multiple documents should be updated (false)
runValidators: if true, runs update validators on this command. Update validators validate the update operation against the model's schema.
setDefaultsOnInsert: if this and upsert are true, mongoose will apply the defaults specified in the model's schema if a new document is created. This option only works on MongoDB >= 2.4 because it relies on MongoDB's $setOnInsert operator.
strict (boolean) overrides the strict option for this update
overwrite (boolean) disables update-only mode, allowing you to overwrite the doc (false)
**/
var option = {
upsert: true // 如果文档里没有则新建,感觉这个可以替代了 save 了...
};
var promise = Blog.update(query, update, option).exec();

删除 remove()

1
var promise = Blog.remove({ _id: id }).exec(); // 略了

统计 count()

1
var promise = Blog.count({ author: 'Kieran' }).exec();

未完待续也可能不续