在Meteor中基于多个parentId查找未完成的最新MongoDB记录
Since Meteor's client-side MongoDB interface only supports find() and findOne(), we can achieve your goal with a combination of a sorted query and simple client-side filtering. Here's a step-by-step breakdown:
Step 1: Fetch All Relevant Records (Sorted by Date)
First, grab all uncompleted records for your target parent IDs, sorted in descending order by createdAt—this ensures the newest records appear first in the results:
const list_of_ids = ["12345akNu", "67890bLoP", ...]; // Your list of parent IDs const allUncompleted = YourCollection.find( { parentId: { $in: list_of_ids }, complete: false // Fixed the field name to match your schema (you wrote "completed" in your query) }, { sort: { createdAt: -1 } } ).fetch();
Step 2: Filter to Keep Only the Latest per ParentId
Next, iterate through the sorted list and capture only the first occurrence of each parentId. Since the results are sorted newest-first, this entry will be the latest uncompleted record for that parent:
const latestPerParent = {}; allUncompleted.forEach(record => { // Only add the record if we haven't already captured this parentId if (!latestPerParent[record.parentId]) { latestPerParent[record.parentId] = record; } }); // Convert to an array if you need a list format instead of an object const latestRecordsArray = Object.values(latestPerParent);
Why This Works
Sorting by createdAt: -1 guarantees that the most recent record for each parentId comes first in the result set. The client-side loop then skips any older entries for the same parentId, leaving you with exactly the latest uncompleted record per parent you requested.
Alternative: Server-Side Method (Optional)
If you want to reduce data transfer to the client, you can create a Meteor server method that uses MongoDB's aggregation framework (supported server-side) to do the filtering before sending results to the client. Here's how that might look:
Server-side method:
Meteor.methods({ 'getLatestUncompletedPerParent'(parentIds) { check(parentIds, [String]); return YourCollection.aggregate([ { $match: { parentId: { $in: parentIds }, complete: false } }, { $sort: { createdAt: -1 } }, { $group: { _id: "$parentId", latestRecord: { $first: "$$ROOT" } } }, { $replaceRoot: { newRoot: "$latestRecord" } } ]); } });
Client-side call:
Meteor.call('getLatestUncompletedPerParent', list_of_ids, (error, result) => { if (error) { // Handle error (e.g., show a notification) } else { const latestRecords = result; // Use your filtered results here } });
This approach cuts down on the amount of data sent over the wire, which is useful if you have a large number of matching records.
内容的提问来源于stack exchange,提问作者Hans

