0

I have an array of Stock objects and try to attach n Report objects to each of the Stock objects:

router.get('/stocks', function (req, res, next) {
    Stock.find({}, function (err, stocks) {
        if (err) {
            next(err)
            return
        }

        async.map(stocks, function (stock, callback) {
            Report.find({ 'isin': stock.isin }).sort('-created').limit(10).exec(function (err, reports) {
                if (err) {
                    next(err)
                    return
                }

                stock.reports = reports
                return callback(null, stock)
            })
        }, function (err, stocks) {
            if (err) {
                next(err)
                return
            }

            res.json(stocks)
        })
    })
})

What I get is the list of stock objects without the reports... What I want is instead the same stocks, but with the additional attribute reports set.

Most interesting is the fact, that console.log(stock) before and after the assignment stock.reports = reports is the same, but console.log(stock.reports) delivers the actual array of report objects...

2 Answers2

1

I found the solution in this other Stackoverflow topic. The solution was the following:

And because mongoose ignores fields that does not exist in the schema...

Because the reports object was not in my stock model, mongoose ignored it... The solution was to add it to mongoose:

const StockSchema = new mongoose.Schema({
    ...
    reports: {
        type: mongoose.Schema.Types.Mixed
    },
    ...
})
Community
  • 1
  • 1
0

Blind shot: Sometimes the "dot. notation" fails if attribute doesn't exist. You could try:

stock['reports'] = reports

instead of

stock.reports = reports
mtsdev
  • 613
  • 5
  • 11
  • I think the word "Sometimes"(You have typo in it!) has nothing to do with programming.. – Rayon Oct 08 '16 at 19:58
  • Probably true. But the fact is that "sometimes" happen and I' never seen a clear list of conditions about it. So for me its only another way of saying "spuriously" or "randomly". And excuse me if this is semantically incorrect. English isn't my mother tongue – mtsdev Oct 08 '16 at 20:01
  • [___JavaScript property access: dot notation vs. brackets?___](http://stackoverflow.com/questions/4968406/javascript-property-access-dot-notation-vs-brackets) – Rayon Oct 08 '16 at 20:04
  • Thanks for your answer, I tried it and it does not change anything. :( – user2493154 Oct 08 '16 at 20:16