在mongodb安装并成功启动后,在项目里面添加mongoose:
npm install mongoose --save
引入并链接mongo
const mongoose = require('mongoose');
const DB_URL = 'mongodb://127.0.0.1:27017';
mongoose.connect(DB_URL);
// 连接成功提示,非必须
mongoose.connection.on('connected', function() {
console.log('mongo connect success');
});
定义文档模型,Schema和model新建模型;
一个数据库文档(表)对应一个模型,通过模型对数据库进行操作。
const User = mongoose.model('user', new mongoose.Schema({
name: {type: String, require: true},
age: {type: Number, require: true}
}));
增 create
删 remove
改 update
查 find、findOne
User.create({
name: '名字',
age: 18
}, function(err, doc) {
if (!err) {
console.log(doc);
}else {
console.log(err);
}
});
User.remove({name: '名字'}, function(err, doc) {
});
User.remove({name: '名字'}, function(err, doc) {
});
User.update({name: '名字'}, {'$set': {age: 22}}, function(err, doc) { // 查询所有
});
User.find({name: '名字'}, function(err, doc) { // 查询name为"名字"的数据,数组
});
User.findOne({name: '名字'}, function(err, doc) { // 查询一个,非数组
});