猫鼬能否直接填充字段而不是嵌套在对象中?

时间:2019-01-25 10:31:11

标签: mongoose

const personSchema = Schema({
  name: String,
  age: Number,
});

const storySchema = Schema({
  author: { type: Schema.Types.ObjectId, ref: 'Person' },
  title: String,
});

在示例中,它输出:

{
  author: {
    name: 'Ken',
    age:  30,
  },
  title: '...',
}

我的预期结果是:

{
  authorName: 'Ken',
  authorAge: 30,
  title: '...',
}

有没有办法做到这一点? 我知道在获得列表后它可以处理,但是我想知道是否需要这样做。

1 个答案:

答案 0 :(得分:0)

那么,可以使用聚合函数和技巧来满足组运算符检索任何对象的首次出现。这个查询可以完成工作:

db.person.aggregate(
  [
    {$group:
       { _id:'$_id',
         authorName: {$first:'$author.name'},
         authorAge:{$first:'$author.age'},
         title:{$first:'$title'}
        }
     }
   ],{cursor:{}})

所以,结果就是这样:

  {
    "_id": ObjectId("5c4af0df17d4bb03faf6e9fe"),
    "authorName": "Julie",
    "authorAge": 40,
    "title": "..."
  },
  {
    "_id": ObjectId("5c4ae86417d4bb03faf6e9fd"),
    "authorName": "Ken",
    "authorAge": 30,
    "title": "..."
  }