深入了解Nodejs中的mongoose工具


本文摘自PHP中文网,作者青灯夜游,侵删。

本篇文章给大家详细介绍一下Nodejs mongoose。有一定的参考价值,有需要的朋友可以参考一下,希望对大家有所帮助。

Mongoose 是在nodejs环境下,对mongodb进行便捷操作的对象模型工具。本文介绍解(翻)密(译)Mongoose插件。

Schema

开始我们就要讲到Schema,一个Schema对应的是mongodb的collection(相当于SQL table),并且定义其结构。

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

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

    }

  });

Schema可用Type:

.String (ex: 'ABCD')

.Number (ex: 123)

.Date (ex: new Date)

.Buffer (ex: new Buffer(0))

.Boolean (ex: false)

.Schema.Types.Mixed (ex: {any:{thing:'ok'}})

.Schema.Types.ObjectId (ex:new mongoose.Types.ObjectID)

.Array (ex:[1,2,3])

.Schema.Types.Decimal128

.Map (ex: new Map([['key','value']]))

我们可以通过一段代码,将Schema转化成Model: mongoose.model(modelName,Schema)

1

var Blog = mongoose.model('Blog', blogSchema);

赋予Schema方法,当方法转成Model的时候,会将方法给予Model

1

2

3

4

5

6

7

//创建一个变量,Schema

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

 

//将方法赋予这个Schema

animalSchema.methods.findSimilarTypes = function(cb) {

    return this.model('Animal').find({ type: this.type }, cb);

};

1

2

3

4

5

6

var Animal = mongoose.model('Animal', animalSchema);

var dog = new Animal({ type: 'dog' });

 

dog.findSimilarTypes(function(err, dogs) {

    console.log(dogs); // woof

});

在Schema方法里,不要使用箭头函数,它会重新绑定this。

赋予Schema static (静态)方法,我们继续使用上面的例子:

1

2

3

4

5

6

7

8

9

//赋予静态方法,可以再Model不实例化的情况下调用

animalSchema.statics.findByName = function(name, cb) {

    return this.find({ name: new RegExp(name, 'i') }, cb);

};

 

var Animal = mongoose.model('Animal', animalSchema);

Animal.findByName('fido', function(err, animals) {

    console.log(animals);

});

Schema索引 index

MongoDB支持二级索引,在mongoose,我们可以将索引定在Schema层。

1

2

3

4

5

6

7

var animalSchema = new Schema({

    name: String,

    type: String,

    tags: { type: [String], index: true } // 声明在字段层

});

 

animalSchema.index({ name: 1, type: -1 }); // 声明在schema层

使用index(二级索引)的时候记得要disable Mongodb 的 autoIndex。

1

2

3

4

5

6

7

mongoose.connect('mongodb://user:pass@localhost:port/database', { autoIndex: false });

  // 或者

mongoose.createConnection('mongodb://user:pass@localhost:port/database', { autoIndex: false });

  // 或者

animalSchema.set('autoIndex', false);

  // 或者

new Schema({..}, { autoIndex: false });

虚拟化

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

// 声明一个Schema

var personSchema = new Schema({

    name: {

      first: String,

      last: String

    }

});

 

// 转成Model

var Person = mongoose.model('Person', personSchema);

 

// 实例化Model

var axl = new Person({

    name: { first: 'Axl', last: 'Rose' }

});

 

//1.如果我们想要打印Person的姓名

console.log(axl.name.first + ' ' + axl.name.last); // Axl Rose

 

//2.使用虚拟化,我们声明一个虚拟字段,然后通过get给其赋值

personSchema.virtual('fullName').get(function () {

  return this.name.first + ' ' + this.name.last;

});

console.log(axl.fullName); // Axl Rose

别名

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

var personSchema = new Schema({

  n: {

    type: String,

    // 给予 n 别名 name,n与name指向同一个值

    alias: 'name'

  }

});

 

// 修改name同样修改n,方向一样

var person = new Person({ name: 'Val' });

console.log(person); // { n: 'Val' }

console.log(person.toObject({ virtuals: true })); // { n: 'Val', name: 'Val' }

console.log(person.name); // "Val"

 

person.name = 'Not Val';

console.log(person); // { n: 'Not Val' }

Model & Documents

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

var Tank = mongoose.model('Tank', yourSchema);

 

var small = new Tank({ size: 'small' });

//使用save的方法

small.save(function (err) {

  if (err) return handleError(err);

  // saved!

});

 

// 或者 使用create

 

Tank.create({ size: 'small' }, function (err, small) {

  if (err) return handleError(err);

  // saved!

});

 

// 或者 使用insertMany/insertOne

Tank.insertMany([{ size: 'small' }], function(err) {

 

});

1

2

3

4

5

//deleteOne 或者 deleteMany

Tank.deleteOne({ size: 'large' }, function (err) {

  if (err) return handleError(err);

  // 只删掉符合项的第一条

});

1

2

3

4

5

Tank.updateOne({ size: 'large' }, { name: 'T-90' }, function(err, res) {

 

});

 

// findOneAndUpdate 查找出相应的数据,修改,并返还给程序

1

2

// 查提供了多种方式,find,findById,findOne,和where

Tank.find({ size: 'small' }).where('createdDate').gt(oneYearAgo).exec(callback);

更多编程相关知识,请访问:编程视频!!

以上就是深入了解Nodejs中的mongoose工具的详细内容,更多文章请关注木庄网络博客

相关阅读 >>

详解多个node版本下如何指定版本运行项目?

深入浅析nodejs里的koa-static中间件

2021年8个值得收藏的nodejs项目

nodejs学习之了解域名解析模块dns

了解nodejs中的可读流

nodejs怎么实现下载excel文件功能?

深入浅析nodejs中的事件和事件循环

node.js安装和配置环境以及部署项目的方法介绍(windows系统下)

谈谈使用nodejs增删改查本地json文件的方法

详细了解nodejs中的事件循环机制

更多相关阅读请进入《nodejs》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...