我正在尝试编写一个mongoose查询,该查询检索一组资产以及这些资产的最新事务。交易与资产分开收集。
为实现此目的,首先我在资产模型中创建了一个虚拟数组,以将资产链接到事务。
schema.virtual('transactions', {
ref: 'transaction',
localField: '_id',
foreignField: '_asset',
justOne: false
})
然后我在node.js express控制器中使用.populate进行查询(注意硬编码的“limit:1”将在某个时刻变为N):
exports.getList = function (req, res) {
Model
.find({}, { __v: 0 })
.populate({
path: 'transactions',
options: { sort: { 'created_at': -1}, limit: 1},
})
.lean()
.exec(function (err, model) {
if (err)
res.send(err);
res.json(model);
});
}
我的测试系统中有3个资产,每个资产都有一堆交易,它返回前两个资产的旧交易,而第三个资产则没有。
当我删除“limit:1”并返回所有交易时,它会正确排序并返回所有三个资产的交易。
我相信我遇到了这个错误:
https://github.com/Automattic/mongoose/issues/4321
关于优雅解决方法的任何想法?
退回所有交易将不是一个可行的长期解决方案。
答案 0 :(得分:5)
这确实是一个卷曲的问题。这里的基础是.populate()
,当然不是“填充虚拟”,不是像你期望的那样工作。
本质上.populate()
本质上是另一个发给MongoDB以检索相关数据的查询。为此,它基本上发出一个$in
的查询,其中包含要匹配的目标的所有“相关字段”值。
"issue 4321"的核心是"sort"
和"limit"
这样的选项,需要通过这样的$in
参数提供的实际查询是事实上,.aggregate()
语句可以“获取为每个键分组的最后n
个结果”。这实际上并不是mongoose目前向MongoDB发布的内容,此时通过可用操作对n
项进行分组也不实际。
您可以手动使用.aggregate()
来解决这个问题,如提供的列表末尾所示,但当然只有少数几种情况。
// Get latest transactions for each master
Transaction.aggregate([
{ '$match': {
'_asset': {
'$in': masters.map(m => m._id)
}
}},
{ '$sort': { '_asset': 1, 'createdAt': -1 } },
{ '$group': {
'_id': '$_asset',
'amount': { '$first': '$amount' },
'createdAt': { '$first': '$createdAt' },
'updatedAt': { '$first': '$updatedAt' },
'did': { '$first': '$_id' }
}},
{ '$project': {
'_id': '$did',
'_asset': '$_id',
'amount': 1,
'createdAt': 1,
'updatedAt': 1
}}
])
这不是很好,也不是一个真正高效的解决方案,但比其他类似的替代方案更好。我相信这是一种更好的方式。
对于你的情况,我怀疑很多类似的情况,你不希望在父文档中包含“完整”事务列表,即使作为引用,因为生成的数组的潜在大小。这种“反模式”通常是“虚拟填充”,实际上是$lookup
旨在避免的。
在“获取最新交易”的特定用例中,这些都不是可行的解决方案。因为两者都基本上需要查看“所有”事务,然后只从它们检索n
结果。
因此,这里的“最新”或实际上“最近”的案例实际上回归到“嵌入”(至少是参考)“有限数量”,以便提供可行的解决方案。因此,建议就是这样做,并在父本身内保留"recent"
个事务列表。这为您提供了包含的场景中的文档,如下所示:
{
"_id" : ObjectId("5959e34adf833e1451a32661"),
"__v" : 0,
"name" : "One",
"recent" : [
ObjectId("5959e34bdf833e1451a32676"),
ObjectId("5959e34bdf833e1451a32674"),
ObjectId("5959e34bdf833e1451a32672"),
ObjectId("5959e34bdf833e1451a32670"),
ObjectId("5959e34bdf833e1451a3266e")
]
}
在此注意到这些并非“全部”相关交易,而只是“最新”交易。关键是只保留一个适合目的的“小”列表。
通过这种方式,您可以直接查询“父”,并只查询"recent"
项所包含的数组$slice
。在列表中我这样做:
Master.find().select({ 'recent': { '$slice': 1 } })
返回数组中的“latest”条目,而不向服务器发送任何其他查询。在这种情况下,它是“最新的”,因为我们在写入"transactions"
集合的同时将“prepend”项添加到此数组中,该集合包含所有内容:
Transaction.create({ _asset: master._id, amount: data.amount })
.then(transaction =>
Master.update(
{ _id: transaction._asset },
{ "$push": {
"recent": {
"$each": [transaction._id],
"$position": 0,
"$slice": 5
}
}}
)
关键元素是父项中数组的$push
,它在数组的开头用$position
修改为“预先读取”,因此“第一个”项始终是“最新的“与父母相关的交易。
然后,此处使用$slice
修饰符将"recent"
数组仅限制为n
项的限制。因此,当添加较新的项目时,“最旧的”项目将被“推离”列表。
此外还有另一个实际目的,即在分页场景中列出“主”和“事务”时,第一个请求可以直接使用"recent"
数组。然后,对新“网页”的其他请求只需通过$nin
过滤出"recent"
数组中包含的项目,并使用常规.skip()
和.limit()
或替代“范围”分页练习,以检索结果的每个“页面”。
要完整演示所有概念,请参阅下面的列表和所有生成的结果。
演示列表:
const async = require('async'),
mongoose = require('mongoose'),
Schema = mongoose.Schema;
mongoose.set('debug',true);
mongoose.Promise = global.Promise;
mongoose.connect('mongodb://localhost/prepend');
const transactionSchema = new Schema({
_asset: { type: Schema.Types.ObjectId, ref: 'Master' },
amount: Number
},{
timestamps: {
createdAt: 'createdAt'
}
});
const Transaction = mongoose.model('Transaction', transactionSchema);
const masterSchema = new Schema({
name: String,
recent: [{ type: Schema.Types.ObjectId, ref: 'Transaction' }]
});
masterSchema.virtual('transactions', {
ref: 'Transaction',
localField: '_id',
foreignField: '_asset',
justOne: false
});
const Master = mongoose.model('Master', masterSchema);
function log(data) {
console.log(JSON.stringify(data, undefined, 2))
}
async.series(
[
// Clean data
(callback) =>
async.each(mongoose.models,(model,callback) =>
model.remove({},callback),callback),
// Create Masters
(callback) =>
Master.insertMany(['One','Two'].map( name => ({ name })),callback),
// Add 10 transactions to each master
(callback) =>
async.each(['One','Two'],(name,callback) =>
async.eachSeries(
Array.apply(null,Array(10)).map((e,i) => ({ name, amount: i+1 })),
(data,callback) => {
Master.findOne({ name: data.name })
.then(master =>
Transaction.create({ _asset: master._id, amount: data.amount })
)
.then(transaction =>
Master.update(
{ _id: transaction._asset },
{ "$push": {
"recent": {
"$each": [transaction._id],
"$position": 0,
"$slice": 5
}
}}
)
)
.then(res => callback())
.catch(callback)
},
callback
),
callback),
// Show populated recent 1 entry only
(callback) =>
Master.find().select({ 'recent': { '$slice': 1 } })
.populate('recent').exec((err,results) => {
if (err) callback(err);
log(results);
callback();
}),
// Populate recent - page 1 then fetch next page
(callback) =>
async.waterfall(
[
(callback) =>
Master.findOne({ name: 'One' }).populate('recent')
.lean()
.exec((err,master) => {
if (err) callback(err);
log(master);
callback(null,{
_asset: master._id,
exclude: master.recent.map( r => r._id )
});
}),
(options,callback) =>
Transaction.find({
_asset: options._asset,
_id: { '$nin': options.exclude }
}).sort({ 'createdAt': -1 }).limit(5)
.exec((err,transactions) => {
if (err) callback(err);
log(transactions)
callback();
})
],
callback
),
// Issue 4321 - Fix - Manual populate with aggregate
(callback) =>
Master.find().select('-recent').exec()
.then(masters => {
// Get latest transactions for each master
Transaction.aggregate([
{ '$match': {
'_asset': {
'$in': masters.map(m => m._id)
}
}},
{ '$sort': { '_asset': 1, 'createdAt': -1 } },
{ '$group': {
'_id': '$_asset',
'amount': { '$first': '$amount' },
'createdAt': { '$first': '$createdAt' },
'updatedAt': { '$first': '$updatedAt' },
'did': { '$first': '$_id' }
}},
{ '$project': {
'_id': '$did',
'_asset': '$_id',
'amount': 1,
'createdAt': 1,
'updatedAt': 1
}}
]).exec((err,transactions) => {
// Map latest transactions to master
masters = masters.map(
m => Object.assign(
m.toObject(),
{
transactions: transactions.filter(
t => t._asset.toHexString() === m._id.toHexString()
)
}
)
);
log(masters);
callback();
})
}).catch(callback)
],
(err) => {
if (err) throw err;
mongoose.disconnect();
}
);
演示输出
Mongoose: transactions.remove({}, {})
Mongoose: masters.remove({}, {})
Mongoose: masters.insertMany([ { __v: 0, name: 'One', _id: 5959e34adf833e1451a32661, recent: [] }, { __v: 0, name: 'Two', _id: 5959e34adf833e1451a32662, recent: [] } ], null)
Mongoose: masters.findOne({ name: 'One' }, { fields: {} })
Mongoose: masters.findOne({ name: 'Two' }, { fields: {} })
Mongoose: transactions.insert({ updatedAt: new Date("Mon, 03 Jul 2017 06:25:14 GMT"), createdAt: new Date("Mon, 03 Jul 2017 06:25:14 GMT"), _asset: ObjectId("5959e34adf833e1451a32662"), amount: 1, _id: ObjectId("5959e34adf833e1451a32663"), __v: 0 })
Mongoose: transactions.insert({ updatedAt: new Date("Mon, 03 Jul 2017 06:25:15 GMT"), createdAt: new Date("Mon, 03 Jul 2017 06:25:15 GMT"), _asset: ObjectId("5959e34adf833e1451a32661"), amount: 1, _id: ObjectId("5959e34adf833e1451a32664"), __v: 0 })
Mongoose: masters.update({ _id: ObjectId("5959e34adf833e1451a32661") }, { '$push': { recent: { '$each': [ ObjectId("5959e34adf833e1451a32664") ], '$slice': 5, '$position': 0 } } }, {})
Mongoose: masters.update({ _id: ObjectId("5959e34adf833e1451a32662") }, { '$push': { recent: { '$each': [ ObjectId("5959e34adf833e1451a32663") ], '$slice': 5, '$position': 0 } } }, {})
Mongoose: masters.findOne({ name: 'One' }, { fields: {} })
Mongoose: masters.findOne({ name: 'Two' }, { fields: {} })
Mongoose: transactions.insert({ updatedAt: new Date("Mon, 03 Jul 2017 06:25:15 GMT"), createdAt: new Date("Mon, 03 Jul 2017 06:25:15 GMT"), _asset: ObjectId("5959e34adf833e1451a32662"), amount: 2, _id: ObjectId("5959e34bdf833e1451a32665"), __v: 0 })
Mongoose: transactions.insert({ updatedAt: new Date("Mon, 03 Jul 2017 06:25:15 GMT"), createdAt: new Date("Mon, 03 Jul 2017 06:25:15 GMT"), _asset: ObjectId("5959e34adf833e1451a32661"), amount: 2, _id: ObjectId("5959e34bdf833e1451a32666"), __v: 0 })
Mongoose: masters.update({ _id: ObjectId("5959e34adf833e1451a32661") }, { '$push': { recent: { '$each': [ ObjectId("5959e34bdf833e1451a32666") ], '$slice': 5, '$position': 0 } } }, {})
Mongoose: masters.update({ _id: ObjectId("5959e34adf833e1451a32662") }, { '$push': { recent: { '$each': [ ObjectId("5959e34bdf833e1451a32665") ], '$slice': 5, '$position': 0 } } }, {})
Mongoose: masters.findOne({ name: 'One' }, { fields: {} })
Mongoose: masters.findOne({ name: 'Two' }, { fields: {} })
Mongoose: transactions.insert({ updatedAt: new Date("Mon, 03 Jul 2017 06:25:15 GMT"), createdAt: new Date("Mon, 03 Jul 2017 06:25:15 GMT"), _asset: ObjectId("5959e34adf833e1451a32662"), amount: 3, _id: ObjectId("5959e34bdf833e1451a32667"), __v: 0 })
Mongoose: transactions.insert({ updatedAt: new Date("Mon, 03 Jul 2017 06:25:15 GMT"), createdAt: new Date("Mon, 03 Jul 2017 06:25:15 GMT"), _asset: ObjectId("5959e34adf833e1451a32661"), amount: 3, _id: ObjectId("5959e34bdf833e1451a32668"), __v: 0 })
Mongoose: masters.update({ _id: ObjectId("5959e34adf833e1451a32661") }, { '$push': { recent: { '$each': [ ObjectId("5959e34bdf833e1451a32668") ], '$slice': 5, '$position': 0 } } }, {})
Mongoose: masters.update({ _id: ObjectId("5959e34adf833e1451a32662") }, { '$push': { recent: { '$each': [ ObjectId("5959e34bdf833e1451a32667") ], '$slice': 5, '$position': 0 } } }, {})
Mongoose: masters.findOne({ name: 'One' }, { fields: {} })
Mongoose: masters.findOne({ name: 'Two' }, { fields: {} })
Mongoose: transactions.insert({ updatedAt: new Date("Mon, 03 Jul 2017 06:25:15 GMT"), createdAt: new Date("Mon, 03 Jul 2017 06:25:15 GMT"), _asset: ObjectId("5959e34adf833e1451a32662"), amount: 4, _id: ObjectId("5959e34bdf833e1451a32669"), __v: 0 })
Mongoose: transactions.insert({ updatedAt: new Date("Mon, 03 Jul 2017 06:25:15 GMT"), createdAt: new Date("Mon, 03 Jul 2017 06:25:15 GMT"), _asset: ObjectId("5959e34adf833e1451a32661"), amount: 4, _id: ObjectId("5959e34bdf833e1451a3266a"), __v: 0 })
Mongoose: masters.update({ _id: ObjectId("5959e34adf833e1451a32661") }, { '$push': { recent: { '$each': [ ObjectId("5959e34bdf833e1451a3266a") ], '$slice': 5, '$position': 0 } } }, {})
Mongoose: masters.update({ _id: ObjectId("5959e34adf833e1451a32662") }, { '$push': { recent: { '$each': [ ObjectId("5959e34bdf833e1451a32669") ], '$slice': 5, '$position': 0 } } }, {})
Mongoose: masters.findOne({ name: 'One' }, { fields: {} })
Mongoose: masters.findOne({ name: 'Two' }, { fields: {} })
Mongoose: transactions.insert({ updatedAt: new Date("Mon, 03 Jul 2017 06:25:15 GMT"), createdAt: new Date("Mon, 03 Jul 2017 06:25:15 GMT"), _asset: ObjectId("5959e34adf833e1451a32662"), amount: 5, _id: ObjectId("5959e34bdf833e1451a3266b"), __v: 0 })
Mongoose: transactions.insert({ updatedAt: new Date("Mon, 03 Jul 2017 06:25:15 GMT"), createdAt: new Date("Mon, 03 Jul 2017 06:25:15 GMT"), _asset: ObjectId("5959e34adf833e1451a32661"), amount: 5, _id: ObjectId("5959e34bdf833e1451a3266c"), __v: 0 })
Mongoose: masters.update({ _id: ObjectId("5959e34adf833e1451a32661") }, { '$push': { recent: { '$each': [ ObjectId("5959e34bdf833e1451a3266c") ], '$slice': 5, '$position': 0 } } }, {})
Mongoose: masters.update({ _id: ObjectId("5959e34adf833e1451a32662") }, { '$push': { recent: { '$each': [ ObjectId("5959e34bdf833e1451a3266b") ], '$slice': 5, '$position': 0 } } }, {})
Mongoose: masters.findOne({ name: 'One' }, { fields: {} })
Mongoose: masters.findOne({ name: 'Two' }, { fields: {} })
Mongoose: transactions.insert({ updatedAt: new Date("Mon, 03 Jul 2017 06:25:15 GMT"), createdAt: new Date("Mon, 03 Jul 2017 06:25:15 GMT"), _asset: ObjectId("5959e34adf833e1451a32662"), amount: 6, _id: ObjectId("5959e34bdf833e1451a3266d"), __v: 0 })
Mongoose: transactions.insert({ updatedAt: new Date("Mon, 03 Jul 2017 06:25:15 GMT"), createdAt: new Date("Mon, 03 Jul 2017 06:25:15 GMT"), _asset: ObjectId("5959e34adf833e1451a32661"), amount: 6, _id: ObjectId("5959e34bdf833e1451a3266e"), __v: 0 })
Mongoose: masters.update({ _id: ObjectId("5959e34adf833e1451a32661") }, { '$push': { recent: { '$each': [ ObjectId("5959e34bdf833e1451a3266e") ], '$slice': 5, '$position': 0 } } }, {})
Mongoose: masters.update({ _id: ObjectId("5959e34adf833e1451a32662") }, { '$push': { recent: { '$each': [ ObjectId("5959e34bdf833e1451a3266d") ], '$slice': 5, '$position': 0 } } }, {})
Mongoose: masters.findOne({ name: 'One' }, { fields: {} })
Mongoose: masters.findOne({ name: 'Two' }, { fields: {} })
Mongoose: transactions.insert({ updatedAt: new Date("Mon, 03 Jul 2017 06:25:15 GMT"), createdAt: new Date("Mon, 03 Jul 2017 06:25:15 GMT"), _asset: ObjectId("5959e34adf833e1451a32662"), amount: 7, _id: ObjectId("5959e34bdf833e1451a3266f"), __v: 0 })
Mongoose: transactions.insert({ updatedAt: new Date("Mon, 03 Jul 2017 06:25:15 GMT"), createdAt: new Date("Mon, 03 Jul 2017 06:25:15 GMT"), _asset: ObjectId("5959e34adf833e1451a32661"), amount: 7, _id: ObjectId("5959e34bdf833e1451a32670"), __v: 0 })
Mongoose: masters.update({ _id: ObjectId("5959e34adf833e1451a32661") }, { '$push': { recent: { '$each': [ ObjectId("5959e34bdf833e1451a32670") ], '$slice': 5, '$position': 0 } } }, {})
Mongoose: masters.update({ _id: ObjectId("5959e34adf833e1451a32662") }, { '$push': { recent: { '$each': [ ObjectId("5959e34bdf833e1451a3266f") ], '$slice': 5, '$position': 0 } } }, {})
Mongoose: masters.findOne({ name: 'One' }, { fields: {} })
Mongoose: masters.findOne({ name: 'Two' }, { fields: {} })
Mongoose: transactions.insert({ updatedAt: new Date("Mon, 03 Jul 2017 06:25:15 GMT"), createdAt: new Date("Mon, 03 Jul 2017 06:25:15 GMT"), _asset: ObjectId("5959e34adf833e1451a32662"), amount: 8, _id: ObjectId("5959e34bdf833e1451a32671"), __v: 0 })
Mongoose: transactions.insert({ updatedAt: new Date("Mon, 03 Jul 2017 06:25:15 GMT"), createdAt: new Date("Mon, 03 Jul 2017 06:25:15 GMT"), _asset: ObjectId("5959e34adf833e1451a32661"), amount: 8, _id: ObjectId("5959e34bdf833e1451a32672"), __v: 0 })
Mongoose: masters.update({ _id: ObjectId("5959e34adf833e1451a32661") }, { '$push': { recent: { '$each': [ ObjectId("5959e34bdf833e1451a32672") ], '$slice': 5, '$position': 0 } } }, {})
Mongoose: masters.update({ _id: ObjectId("5959e34adf833e1451a32662") }, { '$push': { recent: { '$each': [ ObjectId("5959e34bdf833e1451a32671") ], '$slice': 5, '$position': 0 } } }, {})
Mongoose: masters.findOne({ name: 'One' }, { fields: {} })
Mongoose: masters.findOne({ name: 'Two' }, { fields: {} })
Mongoose: transactions.insert({ updatedAt: new Date("Mon, 03 Jul 2017 06:25:15 GMT"), createdAt: new Date("Mon, 03 Jul 2017 06:25:15 GMT"), _asset: ObjectId("5959e34adf833e1451a32662"), amount: 9, _id: ObjectId("5959e34bdf833e1451a32673"), __v: 0 })
Mongoose: transactions.insert({ updatedAt: new Date("Mon, 03 Jul 2017 06:25:15 GMT"), createdAt: new Date("Mon, 03 Jul 2017 06:25:15 GMT"), _asset: ObjectId("5959e34adf833e1451a32661"), amount: 9, _id: ObjectId("5959e34bdf833e1451a32674"), __v: 0 })
Mongoose: masters.update({ _id: ObjectId("5959e34adf833e1451a32661") }, { '$push': { recent: { '$each': [ ObjectId("5959e34bdf833e1451a32674") ], '$slice': 5, '$position': 0 } } }, {})
Mongoose: masters.update({ _id: ObjectId("5959e34adf833e1451a32662") }, { '$push': { recent: { '$each': [ ObjectId("5959e34bdf833e1451a32673") ], '$slice': 5, '$position': 0 } } }, {})
Mongoose: masters.findOne({ name: 'One' }, { fields: {} })
Mongoose: masters.findOne({ name: 'Two' }, { fields: {} })
Mongoose: transactions.insert({ updatedAt: new Date("Mon, 03 Jul 2017 06:25:15 GMT"), createdAt: new Date("Mon, 03 Jul 2017 06:25:15 GMT"), _asset: ObjectId("5959e34adf833e1451a32662"), amount: 10, _id: ObjectId("5959e34bdf833e1451a32675"), __v: 0 })
Mongoose: transactions.insert({ updatedAt: new Date("Mon, 03 Jul 2017 06:25:15 GMT"), createdAt: new Date("Mon, 03 Jul 2017 06:25:15 GMT"), _asset: ObjectId("5959e34adf833e1451a32661"), amount: 10, _id: ObjectId("5959e34bdf833e1451a32676"), __v: 0 })
Mongoose: masters.update({ _id: ObjectId("5959e34adf833e1451a32661") }, { '$push': { recent: { '$each': [ ObjectId("5959e34bdf833e1451a32676") ], '$slice': 5, '$position': 0 } } }, {})
Mongoose: masters.update({ _id: ObjectId("5959e34adf833e1451a32662") }, { '$push': { recent: { '$each': [ ObjectId("5959e34bdf833e1451a32675") ], '$slice': 5, '$position': 0 } } }, {})
Mongoose: masters.find({}, { fields: { recent: { '$slice': 1 } } })
Mongoose: transactions.find({ _id: { '$in': [ ObjectId("5959e34bdf833e1451a32676"), ObjectId("5959e34bdf833e1451a32675") ] } }, { fields: {} })
[
{
"_id": "5959e34adf833e1451a32661",
"__v": 0,
"name": "One",
"recent": [
{
"_id": "5959e34bdf833e1451a32676",
"updatedAt": "2017-07-03T06:25:15.282Z",
"createdAt": "2017-07-03T06:25:15.282Z",
"_asset": "5959e34adf833e1451a32661",
"amount": 10,
"__v": 0
}
]
},
{
"_id": "5959e34adf833e1451a32662",
"__v": 0,
"name": "Two",
"recent": [
{
"_id": "5959e34bdf833e1451a32675",
"updatedAt": "2017-07-03T06:25:15.280Z",
"createdAt": "2017-07-03T06:25:15.280Z",
"_asset": "5959e34adf833e1451a32662",
"amount": 10,
"__v": 0
}
]
}
]
Mongoose: masters.findOne({ name: 'One' }, { fields: {} })
Mongoose: transactions.find({ _id: { '$in': [ ObjectId("5959e34bdf833e1451a32676"), ObjectId("5959e34bdf833e1451a32674"), ObjectId("5959e34bdf833e1451a32672"), ObjectId("5959e34bdf833e1451a32670"), ObjectId("5959e34bdf833e1451a3266e") ] } }, { fields: {} })
{
"_id": "5959e34adf833e1451a32661",
"__v": 0,
"name": "One",
"recent": [
{
"_id": "5959e34bdf833e1451a32676",
"updatedAt": "2017-07-03T06:25:15.282Z",
"createdAt": "2017-07-03T06:25:15.282Z",
"_asset": "5959e34adf833e1451a32661",
"amount": 10,
"__v": 0
},
{
"_id": "5959e34bdf833e1451a32674",
"updatedAt": "2017-07-03T06:25:15.264Z",
"createdAt": "2017-07-03T06:25:15.264Z",
"_asset": "5959e34adf833e1451a32661",
"amount": 9,
"__v": 0
},
{
"_id": "5959e34bdf833e1451a32672",
"updatedAt": "2017-07-03T06:25:15.216Z",
"createdAt": "2017-07-03T06:25:15.216Z",
"_asset": "5959e34adf833e1451a32661",
"amount": 8,
"__v": 0
},
{
"_id": "5959e34bdf833e1451a32670",
"updatedAt": "2017-07-03T06:25:15.195Z",
"createdAt": "2017-07-03T06:25:15.195Z",
"_asset": "5959e34adf833e1451a32661",
"amount": 7,
"__v": 0
},
{
"_id": "5959e34bdf833e1451a3266e",
"updatedAt": "2017-07-03T06:25:15.180Z",
"createdAt": "2017-07-03T06:25:15.180Z",
"_asset": "5959e34adf833e1451a32661",
"amount": 6,
"__v": 0
}
]
}
Mongoose: transactions.find({ _id: { '$nin': [ ObjectId("5959e34bdf833e1451a32676"), ObjectId("5959e34bdf833e1451a32674"), ObjectId("5959e34bdf833e1451a32672"), ObjectId("5959e34bdf833e1451a32670"), ObjectId("5959e34bdf833e1451a3266e") ] }, _asset: ObjectId("5959e34adf833e1451a32661") }, { sort: { createdAt: -1 }, limit: 5, fields: {} })
[
{
"_id": "5959e34bdf833e1451a3266c",
"updatedAt": "2017-07-03T06:25:15.164Z",
"createdAt": "2017-07-03T06:25:15.164Z",
"_asset": "5959e34adf833e1451a32661",
"amount": 5,
"__v": 0
},
{
"_id": "5959e34bdf833e1451a3266a",
"updatedAt": "2017-07-03T06:25:15.135Z",
"createdAt": "2017-07-03T06:25:15.135Z",
"_asset": "5959e34adf833e1451a32661",
"amount": 4,
"__v": 0
},
{
"_id": "5959e34bdf833e1451a32668",
"updatedAt": "2017-07-03T06:25:15.080Z",
"createdAt": "2017-07-03T06:25:15.080Z",
"_asset": "5959e34adf833e1451a32661",
"amount": 3,
"__v": 0
},
{
"_id": "5959e34bdf833e1451a32666",
"updatedAt": "2017-07-03T06:25:15.039Z",
"createdAt": "2017-07-03T06:25:15.039Z",
"_asset": "5959e34adf833e1451a32661",
"amount": 2,
"__v": 0
},
{
"_id": "5959e34adf833e1451a32664",
"updatedAt": "2017-07-03T06:25:15.009Z",
"createdAt": "2017-07-03T06:25:15.009Z",
"_asset": "5959e34adf833e1451a32661",
"amount": 1,
"__v": 0
}
]
Mongoose: masters.find({}, { fields: { recent: 0 } })
Mongoose: transactions.aggregate([ { '$match': { _asset: { '$in': [ 5959e34adf833e1451a32661, 5959e34adf833e1451a32662 ] } } }, { '$sort': { _asset: 1, createdAt: -1 } }, { '$group': { _id: '$_asset', amount: { '$first': '$amount' }, createdAt: { '$first': '$createdAt' }, updatedAt: { '$first': '$updatedAt' }, did: { '$first': '$_id' } } }, { '$project': { _id: '$did', _asset: '$_id', amount: 1, createdAt: 1, updatedAt: 1 } } ], {})
[
{
"_id": "5959e34adf833e1451a32661",
"__v": 0,
"name": "One",
"transactions": [
{
"amount": 10,
"createdAt": "2017-07-03T06:25:15.282Z",
"updatedAt": "2017-07-03T06:25:15.282Z",
"_id": "5959e34bdf833e1451a32676",
"_asset": "5959e34adf833e1451a32661"
}
]
},
{
"_id": "5959e34adf833e1451a32662",
"__v": 0,
"name": "Two",
"transactions": [
{
"amount": 10,
"createdAt": "2017-07-03T06:25:15.280Z",
"updatedAt": "2017-07-03T06:25:15.280Z",
"_id": "5959e34bdf833e1451a32675",
"_asset": "5959e34adf833e1451a32662"
}
]
}
]
答案 1 :(得分:3)
对于在 2021 年阅读本文的人,从 mongoose 5.12.3
起,可以在模型中完成以下操作:
schema.virtual('transactions', {
ref: 'transaction',
localField: '_id',
foreignField: '_asset',
justOne: false,
options: { sort: { 'createdAt': -1}, limit: 1},
})
然后在控制器中:
exports.getList = function (req, res) {
Model
.find({}, { __v: 0 })
.populate({
path: 'transactions',
})
.lean()
.exec(function (err, model) {
if (err)
res.send(err);
res.json(model);
});
}