Something about ThinkJs and Mongoose

栏目: Node.js · 发布时间: 6年前

内容简介:使用mongoose进行查询时的一些稍微复杂的查询方法,由于是初学,也记录一下:mongoose可以通过populate方法直接进行关联查询,例如我们有这样的两个实例:可以直接这样进行关联查询:

使用mongoose进行查询时的一些稍微复杂的查询方法,由于是初学,也记录一下:

关联查询

mongoose可以通过populate方法直接进行关联查询,例如我们有这样的两个实例:

const articleSchema = new Schema({
  title: String,
  category: {
    type: Schema.Types.ObjectId,
    ref: 'Catetory'
  }
})
const cateSchema = new Schema({
  name: String
})

可以直接这样进行关联查询:

articleModel.find({})
  .populate({
    path: 'category',
    match,
    select,
    options
    ...    
  })

聚合查询

可以使用aggregate进行聚合查询

主要聚合的OPERATION可以在 这里 进行查看

比如,针对文章列表,我们想要对其进行时间归档,可以按以下方式查询:

aggregate([{
  $project: {
    time: { $dateToString: { format: "%Y-%m", date: "$create_at" } },
    data: {
      _id: '$_id',
      title: '$title'
    }
  }
}, {
  $group: {
    _id: '$time',
    list: {$push: '$data'}
  }
}, {
  $sort: {
    _id: -1
  }
}])

大体思路就是,使用$project修改文档结构,新增time和data字段,time表示对应的年和月,如2018-07。

然后按照对应的time进行分组,将同组的data插入到一个数组中。

最后按照_id进行排序。最后我们可以输出以下结构的数据了:

  _id: '2018-08',
  list: [{
    _id: 'sdfsdfsdf',
    title: '第一篇文章'
  }, {
    _id: 'sdfaaaaa',
    title: '第二篇'
  }]
}, {
  _id: '2018-08',
  list: [{
    _id: 'sdfsdfsdf',
    title: '第3篇文章'
  }, {
    _id: 'sdfaaaaa',
    title: '第4篇'
  }]
}]

问题

think-mongoose对populate的支持问题

在使用think-mongoose进行populate时,会出现相关的model未进行注册

参考issue

需要在return schema时手动实例对应的model

{
  get schema () {
    const schema = new Schema({
      type: {
        type: Schema.Types.ObjectId,
        ref: `${this.tablePrefix}types`
      }
    })
    think.mongoose('types')
    return schema
  }
}

其中,types是根据model里的文件名称来进行对应的

使用Context.model返回对象无法确定其类型

我们在Controller中,通过this.mongoose()方法获取Model实例,但是返回的对象是通用的MongooseModel,

typescript无法识别真实实例上的方法,我们需要强制对其进行转化。

private getArticleModel(): ArticleModel {
  return this.mongoose('article') as ArticleModel
}

think.Mongoose实例上不能对mongoose的model进行友好提示

看了下think-mongoose的声明文件,针对think.Mongoose的声明如下:

interface MongooseModel {
  new(modelName?: string, config?: object): MongooseModel;
  readonly tablePrefix: string;
  readonly tableName: string;
  models: object;
  mongoose(name: string): MongooseModel;
}

可以看到其未集成mongoose的model声明,我们可以让其集成Model声明,这样在think.Mongoose实例上调用this.find等方法时,就会进行友好的提示及验证了

interface Base extends Document {}
interface MongooseModel extends Model<Base> {...}

以上所述就是小编给大家介绍的《Something about ThinkJs and Mongoose》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Transcending CSS

Transcending CSS

Andy Clarke、Molly E. Holzschlag / New Riders / November 15, 2006 / $49.99

As the Web evolves to incorporate new standards and the latest browsers offer new possibilities for creative design, the art of creating Web sites is also changing. Few Web designers are experienced p......一起来看看 《Transcending CSS》 这本书的介绍吧!

URL 编码/解码
URL 编码/解码

URL 编码/解码

SHA 加密
SHA 加密

SHA 加密工具

HEX HSV 转换工具
HEX HSV 转换工具

HEX HSV 互换工具