mongoose基本操作

在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) { // 查询一个,非数组
 
});
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容