- 创建连接
const mongoose = require('mongoose'); mongoose.connect('mongodb://localhost/test');
- 创建 Schema
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, meta: { votes: Number, favs: Number } });
- 创建 model
var Blog = mongoose.model('Blog', blogSchema);
- 操作——保存
Blog.sold = Date.now(); Blog.save(function (err, product) { if (err) .. })
或
Blog.save().then(function(product) {
...
});
- 操作——查找
MyModel.find({ name: 'john', age: { $gte: 18 }}, function (err, docs) {});
通过 _id 查找
Adventure.findById(id, function (err, adventure) {});
- 操作——更新
MyModel.update({ name: 'Tobi' }, { multi: true }, function (err, raw) {
if (err) return handleError(err);
console.log('The raw response from Mongo was ', raw);
});
- 操作——删除
Model.remove({ artist: 'Anne Murray' }, callback)
- 返回 Promise
query.exec();