Automattic / Automattic/mongoose
Populate in place
- Dominant language
- JavaScript
- Stars
- 27.5k
- Forks
- 4k
- Avg merge
- 2d 7h
- Merged PRs (30d)
- 35
Description
**Do you want to request a *feature* or report a *bug*?**
Question, possibly Feature Request
**What is the current behavior?**
I have a schema like this:
```js
const _id = { type: String, default: uuid } // Can be ignored, just to demonstrate I'm using UUIDs as identifiers due a business rule
const SAuthor = new Schema({ _id, name: { type: String, required: true } })
const SBook = new Schema({ _id, title: { type: String, required: true }, author: { type: String, required: true, ref: 'Author' } })
const MAuthor = model('Author', SAuthor)
const MBook = model('Book', SBook)
// The syntax may sligtly vary, I'm using Typescript and I'm not really sure how this works with plain JS
```
When I make this call: ``await Book.findOneById('xxxx')`` I get the following document:
```js
{
_id: "xxxx",
title: "The Chronicles of Narnia",
author: "yyyy"
}
```
**What is the expected behavior?**
I'd like to know, if executing the above script, is there any way I can get the following document instead?
```js
{
_id: "xxxx",
title: "The Chronicles of Narnia",
author: { _id: "yyyy" }
}
```
and when I call ``xxxx.populate('author')``, so it will load to
```js
{
_id: "xxxx",
title: "The Chronicles of Narnia",
author: { _id: "yyyy", name: "C.S. Lewis" }
}
```
This would help me a lot, because I'm using Apollo for GraphQL, and this would allow me to do do this:
```js
const Resolvers = {
Query: {
bookById = (...) => MBook.findOneById(bookId)
},
Author: { id: e => e._id, name: async e => (await e.populated('name')).name }, // Populate documents on demand
Book: { _id: e => e._id, title: e => e.title, author: e => e.author }
}
```
For instance, the above script would try to pass a String to my Author resolver, and this will crash
**What are the versions of Node.js, Mongoose and MongoDB you are using?**
**NodeJS** v15.14.0
**Mongoose** ~~latest~~ v5.12.14
**MongoDB** 4.2
Contributor guide
Research direction
Start by reproducing the schemas and references shown in the issue, then inspect the MBook.findOneById(), populate(), and populated() behavior in the Mongoose documentation or source. Compare the returned author value before and after population, and verify whether the requested nested shape works with the shown GraphQL resolvers.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- javascript, mongodb, node.js
- Domain
- database
- Issue type
- Feature
- Difficulty
- 3/5
- Estimated time
- 1-2 days
- Activity status
- Stale
- Clarity
- Needs clarification
- Newbie friendliness
- 25/100