【问题标题】:Why mongoose return empty results when I specify the path?当我指定路径时,为什么猫鼬会返回空结果?
【发布时间】:2020-03-26 03:02:10
【问题描述】:

我在 mongoose 中定义了两个模式:DocSchema 具有 DocTypeSchema 引用。

const DocTypeSchema = new Schema({
  name: { type: String, unique: true, index: true }
});

export const DocType = mongoose.model('Doc-Type', DocTypeSchema);


const DocSchema = new Schema(
  {
    name: { type: String },
    type: { type: Schema.Types.ObjectId, ref: 'Doc-Type' },
    description: { type: String },
  }
);

当我尝试获取具有名称类型的文档时,我得到空结果。

我该如何解决这个问题?

 docs.find({ 'type.name': 'VideoBook' }, { limit: 30 })
  • 我不想在 docs 数组中获取 type 对象。只是为了获取与查询匹配的文档。

【问题讨论】:

    标签: node.js mongodb mongoose


    【解决方案1】:

    你需要你的用户.aggregate

    指定集合:

    const DocTypeSchema = new Schema({
      name: { type: String, unique: true, index: true }
    },{ collection: 'docType' });
    

    简单示例:

    const docs = await Doc.aggregate([
        {
            $lookup: {
                from: 'docType',
                localField: 'type',
                foreignField: 'name',
                as: 'magic'
            }
        },
        {$unwind: '$magic'},
        {
            $match: {
                $and: {
                    "magic.name": 'VideoBook'
                }
            }
        },
        { $limit : 30 }
    ])
    

    【讨论】:

    • 加入这个问题,我可以使用find吗?因为我使用express-restify-mongoose,它使用find 函数运行我的查询。
    • @ShlomiLevi 如何与 express-restify-mongoose git聚合
    • 据我所知 find 你不能
    猜你喜欢
    • 2020-02-03
    • 2015-08-04
    • 2014-05-30
    • 2018-08-22
    • 1970-01-01
    • 2012-02-05
    • 1970-01-01
    • 2015-08-26
    相关资源
    最近更新 更多