I can't seem to find a solution for this. I have a collection of users, each user has a subdocument array of payments. I want to be able to load all the payments of all users and add them to a table.
my schema looks like:
Users:
{name: String,
surname: String,
payments: [
{date: Date,
amount: Number}
]}
I have run the following query in the node console and it returns a list of documents:
var allPayments = Users.find( { "payments.amount": { $exists: true }} );
, but when I add it to my route and console log it, I get a Query{} document with my schema not the list of documents. I have tried adding .lean() and.pretty()
but they return errors saying they are not functions, same as when I try to run a forEach() (maybe im doing it wrong).
I have also tried using aggregate as below:
var test = Users.aggregate([{$unwind: '$payments'},{$sort: {'payments.date': 1}},{$group: {_id: 0, 'payments': {$push: '$payments'}}}])
and what I get back is:
Aggregate {
_pipeline:
[ { '$unwind': '$payments' },
{ '$sort': [Object] },
{ '$group': [Object] } ],
_model: Model { Users },
options: {} }
this is my route
router.get('/payments', function(req, res) {
var allPayments = Users.find({
"payments.bank": {
$exists: true
}
});
var test = Users.aggregate([{
$unwind: '$payments'
}, {
$sort: {
'payments.requestdate': 1
}
}, {
$group: {
_id: 0,
'payments': {
$push: '$payments'
}
}
}])
console.log(test)
console.log(allPayments)
});
So I solved the issue by changing my schemas, I basically made payment I to its own schema and then included the user ID into each payment that is created. Then I just ran a db. Collection. Find() to load all payments
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.