84550694 2019-06-27
小萌新 []~( ̄▽ ̄)~*,如有不对的地方还请指正npm install mongoose 或者 yarn add mongoose
该实例来自于官网文档首页
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test');
const Cat = mongoose.model('Cat', { name: String });
const kitty = new Cat({ name: 'Zildjian' });
kitty.save().then(() => console.log('meow'));采用了ES6的语言标准,不了解的同学可以看一下阮一峰的《ES6标准入门》
1 引用 mongoose 以及连接数据库
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test');2 监听连接状态
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
// we're connected!
});3 Schema 模式
Mongoose将数据对应模式, 约定了Model中数据的类型,比如下列代码中name这个属性只能是字符串数据传入
var kittySchema = mongoose.Schema({
name: String
});4 Model 模型
模型有点像是mongodb中的collection,可以在model上进行CURD(Create/Update/Read/Delete)的操作
var Kitten = mongoose.model('Kitten', kittySchema);接下来讲解CURD这四个基础操作
5 Create 创建一个数据对象(注意后面还需要save一下)
var silence = new Kitten({ name: 'Silence' });
console.log(silence.name); // 'Silence'6 为数据对象增加函数
// NOTE: methods must be added to the schema before compiling it with mongoose.model()
kittySchema.methods.speak = function () {
var greeting = this.name
? "Meow name is " + this.name
: "I don't have a name";
console.log(greeting);
}
var Kitten = mongoose.model('Kitten', kittySchema);使用该函数
var fluffy = new Kitten({ name: 'fluffy' });
fluffy.save(function (err, fluffy) {
if (err) return console.error(err);
fluffy.speak();
});7 Update 更新数据
未完待续
8 Read 查询数据
//查询所有数据
Kitten.find(function (err, kittens) {
if (err) return console.error(err);
console.log(kittens);
})//正则条件查询
Kitten.find({ name: /^fluff/ }, callback);9 Delete 删除数据
未完待续