您好,欢迎访问一九零五行业门户网

使用Nodejs mongoose案例解析(附代码)

这次给大家带来使用nodejs mongoose案例解析(附代码),使用nodejs mongoose的注意事项有哪些,下面就是实战案例,一起来看一下。
前言
mongoose 是在nodejs环境下,对mongodb进行便捷操作的对象模型工具。本文介绍解(翻)密(译)mongoose插件。
schema
开始我们就要讲到schema,一个schema对应的是mongodb的collection(相当于sql table),并且定义其结构。
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)
var blog = mongoose.model('blog', blogschema);
赋予schema方法,当方法转成model的时候,会将方法给予model
//创建一个变量,schemavar animalschema = new schema({ name: string, type: string });//将方法赋予这个schemaanimalschema.methods.findsimilartypes = function(cb) {  return this.model('animal').find({ type: this.type }, cb);};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 (静态)方法,我们继续使用上面的例子:
//赋予静态方法,可以再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层。
var animalschema = new schema({  name: string,  type: string,  tags: { type: [string], index: true } // 声明在字段层});animalschema.index({ name: 1, type: -1 }); // 声明在
使用index(二级索引)的时候记得要disable mongodb 的 autoindex。
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 });
虚拟化
// 声明一个schemavar personschema = new schema({  name: {   first: string,   last: string  }});// 转成modelvar person = mongoose.model('person', personschema);// 实例化modelvar 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
别名
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); // valperson.name = 'not val';console.log(person); // { n: 'not val' }model & documents

var tank = mongoose.model('tank', yourschema);var small = new tank({ size: 'small' });//使用save的方法small.save(function (err) { if (err) return handleerror(err); // saved!});// 或者 使用createtank.create({ size: 'small' }, function (err, small) { if (err) return handleerror(err); // saved!});// 或者 使用insertmany/insertonetank.insertmany([{ size: 'small' }], function(err) {});

//deleteone 或者 deletemanytank.deleteone({ size: 'large' }, function (err) { if (err) return handleerror(err); // 只删掉符合项的第一条});

tank.updateone({ size: 'large' }, { name: 't-90' }, function(err, res) {});// findoneandupdate 查找出相应的数据,修改,并返还给程序

// 查提供了多种方式,find,findbyid,findone,和wheretank.find({ size: 'small' }).where('createddate').gt(oneyearago).exec(callback);
相信看了本文案例你已经掌握了方法,更多精彩请关注其它相关文章!
推荐阅读:
angular2使用dom有哪些注意事项
如何在项目中使用vue+slot插口
以上就是使用nodejs mongoose案例解析(附代码)的详细内容。
其它类似信息

推荐信息