i have query looks so:
var writer = writers.findone({ _id: writerid, books: { $elemmatch: { id: books.findone({ slug: bookslug })._id } } });
however, return full list of classes in query.
{ name: "h.p. lovecraft", books: [{ id: "1234", slug: "at-the-mountains-of-madness" }, { id: "5678", slug: "herbert-west-reanimator" }] }
would there way eliminate information except 1 item in list want , make object? say, want final result be:
{ name: "h.p lovecraft", book: { id: "1234", slug: "herbert-west-reanimator" } }
how done in meteor mongodb?
one approach take use $elemmatch
projection operator findone() query. document _id
equal writerid
, $elemmatch
projection returns first matching element array:
var bookid = books.findone({ slug: bookslug })._id, writer = writers.findone({ _id: writerid }, { books: { $elemmatch: { id: bookid } }, _id: 0, name: 1 } );
another approach use underscore library's _.find()
method return specific array element:
var bookid = books.findone({ slug: bookslug })._id, writer = writers.findone({ _id: writerid, books: { $elemmatch: { id: bookid } } }), book = _.find(writer.books, function(book) {return book.id === bookid});