say I have two arrays:
authors = [
{
name: 'Robert Martin',
id: "afa51ab0-344d-11e9-a414-719c6709cf3e",
born: 1952,
},
{
name: 'Martin Fowler',
id: "afa5b6f0-344d-11e9-a414-719c6709cf3e",
born: 1963
}
]
let books = [
{
title: 'Clean Code',
published: 2008,
author: 'Robert Martin',
id: "afa5b6f4-344d-11e9-a414-719c6709cf3e",
genres: ['refactoring']
},
{
title: 'Agile software development',
published: 2002,
author: 'Robert Martin',
id: "afa5b6f5-344d-11e9-a414-719c6709cf3e",
genres: ['agile', 'patterns', 'design']
},
{
title: 'Refactoring, edition 2',
published: 2018,
author: 'Martin Fowler',
id: "afa5de00-344d-11e9-a414-719c6709cf3e",
genres: ['refactoring']
}
]
const Book = require('./controllers/book')
const Author = require('./controllers/author')
using mongoose object schema, book object's author property wants to be populated with complete author object if book.author === author.name.
like this:
{
title: 'Clean Code',
published: 2008,
author: {
name: 'Robert Martin',
id: "afa51ab0-344d-11e9-a414-719c6709cf3e",
born: 1952,
},
id: "afa5b6f4-344d-11e9-a414-719c6709cf3e",
genres: ['refactoring']
},
I have tried this:
books.forEach(book => {
const bookAuthor = authors.find(author => book.author === author.name).name
Book.findOne({author: bookAuthor}).populate('author') }
no success, somehow js is hard to manipulate data structure on the fly than Python I feel. Could you help?