登录  /  注册
首页 > web前端 > js教程 > 正文

Node.js的MongoDB驱动Mongoose基本使用教程_node.js

php中文网
发布: 2016-05-16 15:12:43
原创
1548人浏览过

使用mongoose可以让我们更好使用mongodb数据库,而不需要写繁琐的业务逻辑。

安装

npm install mongoose
登录后复制

初始化使用
使用mongoose前,需安装node和mongodb,这里不讲node和mongodb的安装方法。

 var mongoose = require("mongoose");
 var Schema = mongoose.Schema;
 var db = mongoose.connection;
 mongoose.connect('mongodb://localhost/animal');
 db.on('error', console.error);
 db.once('open', function() {
  //这里建立模式和模型
 }
登录后复制

快速入门
在mongoose中,所有的数据都是一种模式,每个模式都映射到mongodb的集合,并且定义该集合文件结构。

 //这里建立一个动物的模式,所有动物都拥有这个模式下的所有属性
 var animalSchema = new Schema({
  name: String,
  age: Number,
 });
登录后复制

模型是我们从Schema中定义的一种多样化的构造函数,模型的实例可以使用很多操作,所有文档的创建和检索都是由模型来处理

 var animalMode = db.model('Animal', animalSchema);
登录后复制

模型的实例实质是文件,而我们可以很轻松创建、修改这种文件

 var cat = new animalMode({
  name: 'catName',
  age: '7', //这里依然使用字符串,mongoose会自动转换类型
  });

 cat.save(function(err, thor) {
  if (err) return console.log(err);
  console.log(thor);
 });
 //或者可以使用create
 //cat.create(function(err, thor) {
 // if (err) return console.log(err);
 // console.log(thor);
 //});

 //执行查找
 animalMode.find(function(err, people){
  if(err) console.log(err);
  console.log(people);
 });
 //查找符合条件数据
 animalMode.findOne({title: 'catName'}, function(err, cat){
  if(err) console.log(err);
  console.log(cat);
 });

登录后复制

Schema
数据类型

这是Schema中所有的数据类型,包括mongoose自定的数据类型

  • String
  • Number
  • Date
  • Buffer
  • Boolean
  • Mixed
  • ObjectId
  • Array

每种数据类型的使用

 var animalMode = mongoose.model('Animal', schema);

 var cat = new animalMode;
 cat.name = 'Statue of Liberty'    //String
 cat.age = '7';        //Number
 cat.updated = new Date;      //Date
 cat.binary = new Buffer(0);     //Buffer
 cat.living = false;       //Boolean
 cat.mixed = { any: { thing: 'i want' } }; //Mixed    
 cat._someId = new mongoose.Types.ObjectId; //ObjectId
 cat.ofString.push("strings!");    //Array

登录后复制

其中Mixed是mongoose自定义的一种混合类型,因为Mixed没有定义具体内容,可以用{}来使用,以下2种定义形式等价。

 var animalSchema = new Schema({any: {}});
 var animalSchema = new Schema({any: {Schema.Types.Mixed}});
登录后复制

自定义方法

可以为Schema绑定方法

 var animalSchema = new Schema({
  name: String,
  age: Number,
 });

 animalSchema.methods.findSimilarTypes = function (cb) {
  return this.model('Animal').find({ name: this.name }, cb);
 }

 var animalMode = db.model('Animal', animalSchema);

 cat.findSimilarTypes(function(err, cat){
  if(err) console.log(err);
  console.log(cat);
 });

登录后复制

也可以为Schema添加静态方法

 animalSchema.statics.findByName = function (name, cb) {
  return this.find({ name: new RegExp(name, 'i') }, cb);
 }
 var animalMode = db.model('Animal', animalSchema);

 animalMode.findByName('catName', function (err, animals) {
  console.log(animals);
 });

登录后复制

索引

我们可以为mongodb数据建立索引,mongodb支持二级索引,为了提高数据查找和定位,建立复合索引是必要的

 var animalSchema = new Schema({
  name: String,
  age: Number,
  tags: { age: [String], index: true } // field level
 });

 animalSchema.index({ name: 1, age: -1 }); // schema level

登录后复制

但是这种索引的建立可能导致显著的性能影响,建议在生产下停止,将设置模式下的自动索引设置为false禁止

 animalSchema.set('autoIndex', false);
 // or
 new Schema({..}, { autoIndex: false });
登录后复制

Model
C

 cat.save(function(err, thor) {
  if (err) return console.log(err);
  console.log(thor);
 });
 //或者可以使用create
 cat.create(function(err, thor) {
  if (err) return console.log(err);
  console.log(thor);
 });
登录后复制

R

//find
animalMode.find(function(err, cat){
 if (err) console.log(err);
 console.log(cat);
})

//findOne
animalMode.findOne({name: 'catName'}, function(err, cat){
 if (err) console.log(err);
 console.log(cat);
})

//findByID
//与 findOne 相同,但它接收文档的 _id 作为参数,返回单个文档。_id //可以是字符串或 ObjectId 对象。
animalMode.findById(id, function(err, adventure){
 if (err) consoel.log(err);
 console.log(adventure);
});

//where
//查询数据类型是字符串时,可支持正则
animalMode.where('age', '2').exec(function(err, cat){
 if (err) console.log(err);
 console.log(cat);
});

animalMode
 .where('age').gte(1).lte(10)
 .where('name', 'catName')
 .exec(function(err, cat){
  if (err) console.log(err);
  console.log(cat);
 });

登录后复制

U
官方文档提供的更新函数Model.update

Model.update(conditions, doc, [options], [callback])

  • conditions 更新条件
  • doc 更新内容
  • option 更新选项
  • safe (boolean) 安全模式,默认选项,值为true
  • upsert (boolean) 条件不匹配时是否创建新文档,默认值为false
  • multi (boolean) 是否更新多个文件,默认值为false
  • strict (boolean) 严格模式,只更新一条数据
  • overwrite (boolean) 覆盖数据,默认为false
  • callback
  • err 更新数据出错时返回值
  • numberAffected (笔者暂时不清楚)
  • rawResponse 受影响的行数
animalMode.update({name: 'catName'}, {age: '6'}, {multi : true}, function(err, numberAffected, raw){
 if (err) return console.log(err);
 console.log('The number of updated documents was %d', numberAffected);
 console.log('The raw response from Mongo was ', raw);
});
登录后复制

D

animalMode.remove({age: 6}, function(err){
 if (err) console.log(err);
})
登录后复制

其它
//返回文档数

animalMode.count({age: 2}, function(err, cat){
 if (err) console.log(err);
 console.log(cat);
})
登录后复制

智能AI问答
PHP中文网智能助手能迅速回答你的编程问题,提供实时的代码和解决方案,帮助你解决各种难题。不仅如此,它还能提供编程资源和学习指导,帮助你快速提升编程技能。无论你是初学者还是专业人士,AI智能助手都能成为你的可靠助手,助力你在编程领域取得更大的成就。
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2024 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号