Ayubx
Ayubx

Reputation: 665

How to get data from a mongoose aggregate query in nodejs

The mongoose query is fetching the correct results but i am unable to access the data.

I want to get the current max id in the database, increment the value by 1 and save the data to the database

// add a new book
router.route('/books/add').post(jsonParser, (req, res) => {

Book.aggregate([{ $group: { _id: "id", id: { $max: "$id" } } }], (err, books) => {
    if (!books)
        return next(new Error("Could not load book!"))
    else {
        let book = new Book(req.body);

        // log the max id returned, currently returns undefined
        console.log("Id found  ", books.id);

        book.id = books.id + 1;
        console.log("BookId ", book.id);

        res.status(200).json({ 'book': 'Added successfully!' });
        // book.save().then(book => {
        //     res.status(200).json({ 'book': 'Added successfully!' });
        // }).catch(err => {
        //     res.status(400).send('Failed to create new record.');

        // });
    }
});

});

console.log(books.id) returns undefined whereas console.log(books) does show me the result which is [ { _id: 'id', id: 5 } ]. What i want to do is get the id i.e. 5, how do i do that ? Thank you.

Upvotes: 0

Views: 159

Answers (1)

Sanjay Kumar N S
Sanjay Kumar N S

Reputation: 4739

The aggregate query result is an array,, and you have to use the zero index to get the first element which is an object contains your result. Try this:

console.log(books[0].id)

Upvotes: 2

Related Questions