使用 ES6 的语法继承该类
使用普通方式继承该类
  1. module.exports = think.model('mongo', {
  2. getList: function(){
  3. }
  4. })

model.fields

设置字段,如:

  1. export default class extends think.model.mongo {
  2. init(...args){
  3. super.init(...args);
  4. //设置字段
  5. this.fields = {
  6. name: {
  7. type: 'string'
  8. },
  9. pwd: {
  10. type: 'string'
  11. }
  12. }
  13. }

:目前框架并不会对字段进行检查。

model.indexes

设置字段索引,数据操作之前会自动创建索引。

  1. export default class extends think.model.mongo {
  2. init(...args){
  3. super.init(...args);
  4. //配置索引
  5. this.indexes = {
  6. }
  7. }
  8. }
单字段索引
唯一索引
  1. init(...args){
  2. super.init(...args);
  3. //配置索引
  4. this.indexes = {
  5. name: {$unique: 1}
  6. }
  7. }
  8. }
多字段索引

可以将多个字段联合索引,如:

  1. export default class extends think.model.mongo {
  2. init(...args){
  3. super.init(...args);
  4. //配置索引
  5. this.indexes = {
  6. email: 1
  7. test: {
  8. name: 1,
  9. title: 1,
  10. $unique: 1
  11. }
  12. }
  13. }
  14. }

model.pk

主键名,默认为 _id,可以通过 this.getPk 方法获取。

方法

model.where(where)

mongo 模型中的 where 条件设置和关系数据库中不太一样。

等于判断
  1. export default class extends think.model.mongo {
  2. where1(){
  3. return this.where({ type: "snacks" }).select();
  4. }
AND 条件
OR 条件
  1. export default class extends think.model.mongo {
  2. return this.where({
  3. $or: [ { qty: { $gt: 100 } }, { price: { $lt: 9.95 } } ]
  4. }).select();
  5. }
  6. where2(){
  7. return this.where({
  8. type: 'food',
  9. $or: [ { qty: { $gt: 100 } }, { price: { $lt: 9.95 } } ]
  10. }).select();
  11. }
  12. }
内嵌文档
  1. export default class extends think.model.mongo {
  2. where1(){
  3. return this.where( {
  4. producer:
  5. {
  6. company: 'ABC123',
  7. address: '123 Street'
  8. }
  9. }).select();
  10. }
  11. where2(){
  12. return this.where({ 'producer.company': 'ABC123' } ).select();
  13. }
  14. }
IN 条件
  1. export default class extends think.model.mongo {
  2. where1(){
  3. return this.where({ type: { $in: [ 'food', 'snacks' ] } }).select();
  4. }
  5. }

model.collection()

  • return {Promise}
    获取操作当前表的句柄。

model.aggregate(options)

聚合查询。具体请见 。

model.mapReduce(map, reduce, out)

mapReduce 操作,具体请见 。

model.createIndex(indexes, options)

  • indexes {Object} 索引配置
  • options {Object}
    创建索引。

model.getIndexes()

  • return {Promise}
    获取索引。