How to get filtered data from entities in coredata - core-data

I have a scenario where I know what I need to do but do not know how to implement it in Swift...
I have 2 tables in CoreData and I fetch their values as below
What I need - all friends that are in a particular user friends array
//-----Full Code
Manual CachedUser Class
import Foundation
import CoreData
extension CachedUser {
#nonobjc public class func fetchRequest() -> NSFetchRequest<CachedUser> {
return NSFetchRequest<CachedUser>(entityName: "CachedUser")
}
#NSManaged public var name: String?
#NSManaged public var id: String?
#NSManaged public var company: String?
#NSManaged public var isActive: Bool
#NSManaged public var age: Int16
#NSManaged public var email: String?
#NSManaged public var address: String?
#NSManaged public var about: String?
#NSManaged public var registered: String?
#NSManaged public var tags: String?
#NSManaged public var friends: NSSet?
public var wrappedName: String {
name ?? "Name N/A"
}
public var wrappedId: String {
id ?? "id N/A"
}
public var wrappedCompany: String {
company ?? "comapny N/A"
}
public var wrappedIsActive: Bool {
isActive
}
public var checkIsActive: String {
return isActive ? "YES" :"NO"
}
public var wrappedEmail: String {
email ?? "email N/A"
}
public var wrappedAge: Int16 {
age
}
public var wrappedRegistered: String {
registered ?? "N/A"
}
public var cachedFriend: [CachedFriend] {
let set = friends as? Set<CachedFriend> ?? []
return set.sorted {
$0.wrappedName < $1.wrappedName
}
}
}
// MARK: Generated accessors for friends
extension CachedUser {
#objc(addFriendsObject:)
#NSManaged public func addToFriends(_ value: CachedFriend)
#objc(removeFriendsObject:)
#NSManaged public func removeFromFriends(_ value: CachedFriend)
#objc(addFriends:)
#NSManaged public func addToFriends(_ values: NSSet)
#objc(removeFriends:)
#NSManaged public func removeFromFriends(_ values: NSSet)
}
extension CachedUser : Identifiable {
}
//-----
//----- CachedUSer
import Foundation
import CoreData
extension CachedFriend {
#nonobjc public class func fetchRequest() -> NSFetchRequest<CachedFriend> {
return NSFetchRequest<CachedFriend>(entityName: "CachedFriend")
}
#NSManaged public var name: String?
#NSManaged public var id: String?
#NSManaged public var users: CachedUser?
public var wrappedId: String {
id ?? "Unknown Id"
}
public var wrappedName: String {
name ?? "Unknown Name"
}
}
extension CachedFriend : Identifiable {
}
//------
//---SwiftUI View where I want the data , Section friends does not show any friends
import SwiftUI
struct DetailView: View {
let users: [CachedUser]
let user: CachedUser
#State var friendsArray: [CachedFriend] = []
#FetchRequest(sortDescriptors: []) var friendsData: FetchedResults<CachedFriend>
var body: some View {
Form {
List {
Section("Name") {
Text(user.wrappedName)
.font(.body)
}
Section("email") {
Text(user.wrappedEmail)
}
Section("Registration Date") {
Text(user.wrappedRegistered)
}
Section("Company") {
Text(user.wrappedCompany)
}
Section("Is Active") {
Image(systemName: user.isActive ? "checkmark.circle.fill" : "xmark.octagon.fill")
.foregroundColor(user.isActive ? Color.green : Color.red)
}
Section("Friends") {
List {
ForEach(friendsArray, id:\.self) {friend in
Text(friend.wrappedName)
}
}
}
}
.onAppear {
friendsArray = Array(user.cachedFriend)
}
}
}
}
//-----End
Here I have a CachedUser Entity and CachedFriend Entity Image of Relationship attached .
Every user has an array of friends that I get from json file , that friend array contains name and id....
I know I have to loop over the friends table and filter all names that have the same name as in User Friends array, but I just cannot seem to do it, I have tried below , but they just do not work , can any one point me in right direction. Thanks
#State var friendsArray: [CachedFriend] = []
let user: CachedUser
func findFriend() {
for allFriend in friendsData {
friendsArray = user.cachedFriend.filter({ item in
item.wrappedId == allFriend.wrappedId
})
}
print(friendsArray.count)
}
Sample of json
[
{
"id": "50a48fa3-2c0f-4397-ac50-64da464f9954",
"isActive": false,
"name": "Alford Rodriguez",
"age": 21,
"company": "Imkan",
"email": "alfordrodriguez#imkan.com",
"address": "907 Nelson Street, Cotopaxi, South Dakota, 5913",
"about": "Occaecat consequat elit aliquip magna laboris dolore laboris sunt officia adipisicing reprehenderit sunt. Do in proident consectetur labore. Laboris pariatur quis incididunt nostrud labore ad cillum veniam ipsum ullamco. Dolore laborum commodo veniam nisi. Eu ullamco cillum ex nostrud fugiat eu consequat enim cupidatat. Non incididunt fugiat cupidatat reprehenderit nostrud eiusmod eu sit minim do amet qui cupidatat. Elit aliquip nisi ea veniam proident dolore exercitation irure est deserunt.",
"registered": "2015-11-10T01:47:18-00:00",
"tags": [
"cillum",
"consequat",
"deserunt",
"nostrud",
"eiusmod",
"minim",
"tempor"
],
"friends": [
{
"id": "91b5be3d-9a19-4ac2-b2ce-89cc41884ed0",
"name": "Hawkins Patel"
},
{
"id": "0c395a95-57e2-4d53-b4f6-9b9e46a32cf6",
"name": "Jewel Sexton"
},
{
"id": "be5918a3-8dc2-4f77-947c-7d02f69a58fe",
"name": "Berger Robertson"
},
{
"id": "f2f86852-8f2d-46d3-9de5-5bed1af9e4d6",
"name": "Hess Ford"
},
{
"id": "6ba32d1b-38d7-4b0f-ba33-1275345eacc0",
"name": "Bonita White"
},
{
"id": "4b9bf1e5-abec-4ee3-8135-3a838df90cef",
"name": "Sheryl Robinson"
},
{
"id": "5890bacd-f49c-4ea2-b8fa-02db0e083238",
"name": "Karin Collins"
},
{
"id": "29e0f9ee-71f2-4043-ad36-9d2d6789b2c8",
"name": "Pace English"
},
{
"id": "aa1f8001-59a3-4b3c-bf5e-4a7e1d8563f2",
"name": "Pauline Dawson"
},
{
"id": "d09ffb09-8adc-48e1-a532-b99ae72473d4",
"name": "Russo Carlson"
},
{
"id": "7ef1899e-96e4-4a76-8047-0e49f35d2b2c",
"name": "Josefina Rivas"
}
]
},

You don't need to use filter on a CoreData FetchRequest ever.
It is best to do the filtering by NSPredicate
https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/CoreData/index.html
But in this case all the user's friends are in a variable. If you have the individual user all you need to do is something like this...
user.friends.allObjects

Related

Mongodb filter by categories

I have Product collection. In this collection each document has same keys and different values.
Several documents are shown in the example below.
[
{
"productCategory": "Electronics",
"price": "20",
"priceCondition": "Fixed",
"adCategory": "Sale",
"productCondition": "New",
"addDescription": "Lorem Ipsum Dolor Sit Amet Consectetur Adipisicing Elit Maxime Ab Nesciunt Dignissimos.",
"city": "Los Angeles",
"rating": {
"oneStar": 1,
"twoStar": 32,
"threeStar": 13,
"fourStar": 44,
"fiveStar": 1
},
"click": 12,
"views": 3
},
{
"productCategory": "Automobiles",
"price": "1500",
"priceCondition": "Negotiable",
"adCategory": "Rent",
"productCondition": "New",
"addDescription": "Lorem Ipsum Dolor Sit Amet Consectetur Adipisicing Elit
Maxime Ab Nesciunt Dignissimos.",
"city": "California",
"rating": {
"oneStar": 2,
"twoStar": 13,
"threeStar": 10,
"fourStar": 50,
"fiveStar": 4
},
"click": 22,}
},
{
"productCategory": "Hospitality",
"price": "500",
"priceCondition": "Yearly",
"adCategory": "Booking",
"productCondition": "New",
"addDescription": "Lorem Ipsum Dolor Sit Amet Consectetur Adipisicing Elit Maxime Ab Nesciunt Dignissimos.",
"city": "Houston",
"rating": {
"oneStar": 16,
"twoStar": 19,
"threeStar": 28,
"fourStar": 16,
"fiveStar": 17
},
"click": 102,
"views": 47
}
]
I would like to search each document with one or more matching search queries to match the document with my search.
In the example below, I will show url query:
http://localhost:8080/api/v1/filter?productCondition=New&price=100&productCategory=Hospitality
So far I have tried to solve the filtration using the $or and $and operators but here there is a problem because with the first operator $or when I do a query only the first condition is searched, the rest is omitted, with the second operator $and I have to add all the condition and the problem arises because I will not always have all querys.
I am using the find method to achieve my filtering methods.
db.collection(Index.Add)
.find({
$or: [
{ productCategory },
{ price },
{ adCategory },
{ priceCondition },
{ productCondition },
{ city },
],
})
.limit(pageSize)
.skip(pageSize * parsePage)
.toArray();
db.collection(Index.Add)
.find({
$and: [
{ productCategory },
{ price },
{ adCategory },
{ priceCondition },
{ productCondition },
{ city },
],
})
.limit(pageSize)
.skip(pageSize * parsePage)
.toArray();
From what I understand, you're trying to build filters for your products listing API. On any listing page, if one applies two or more simultaneous filters one expects an and of all those filters. So, a query like this productCondition=New&price=100 should get all the products where productCondition is New and price is 100.
Therefore, in order to filter we should go for an $and operator in find query. As you rightly said you might not have all the query params in your path always, so a condition like this:
$and: [
{ productCategory },
{ price },
{ adCategory },
{ priceCondition },
{ productCondition },
{ city },
]
would send null or undefined to the database values for the keys that don't exist in the query param and you might get unexpected results.
To handle this, you should build the $and query based upon what is there in your query params like this (assuming you're using express.js):
let conditions = [];
for(const param in req.query) {
if(req.query[param]) {
conditions.push({ param: req.query[param] });
}
}
conditions will only contain the keys whose values are there in the query params. You can then pass the conditions variable to the query like this:
db.collection(Index.Add)
.find({
$and: conditions
})
.limit(pageSize)
.skip(pageSize * parsePage)
.toArray();
Thank you for bringing me to a solution. My solution is a banned query that is undefined. And just apply the valid query to find method.
Example:
const {
page,
productCategory,
price,
priceCondition,
adCategory,
productCondition,
city,
}: IAdds = req.query;
const check = (object: IAdds) => {
for (let key in {
productCategory,
price,
priceCondition,
adCategory,
productCondition,
city,
}) {
if (object[key] !== undefined) return req.query;
}
};
const resultFromCheckQuey = check(req.query);
const { page, ...res } = resultFromCheckQuey;
const filterResult = await db
.collection(Index.Add)
.find({
$and: [res],
})
.limit(pageSize)
.skip(pageSize * parsePage)
.toArray();

Filtering array by ISODate by Month in nodejs and express

given this array of objects:
[
{
"name": "Fixflex",
"description": "Duis mattis egestas metus. Aenean fermentum. Donec ut mauris eget massa tempor convallis. Nulla neque libero, convallis eget, eleifend luctus, ultricies eu, nibh. Quisque id justo sit amet sapien dignissim vestibulum.",
"category": "c7",
"startDate": { "$date": "2021-05-12T19:17:52.000Z" }
},
{
"name": "Fixflex",
"description": "In congue. Etiam justo. Etiam pretium iaculis justo.",
"category": "c3",
"startDate": { "$date": "2020-11-07T09:47:00.000Z" }
},
{
"name": "Cookley",
"description": "Nunc purus. Phasellus in felis. Donec semper sapien a libero. Nam dui. Proin leo odio, porttitor id, consequat in, consequat ut, nulla. Sed accumsan felis.",
"category": "c6",
"startDate": { "$date": "2020-03-07T10:09:39.000Z" }
},
{
"name": "Bigtax",
"description": "Morbi non quam nec dui luctus rutrum. Nulla tellus. In sagittis dui vel nisl. Duis ac nibh. Fusce lacus purus, aliquet at, feugiat non, pretium quis, lectus. Suspendisse potenti.",
"category": "c7",
"startDate": { "$date": "2020-09-14T23:51:53.000Z" }
},
{
"name": "Alphazap",
"description": "Vestibulum quam sapien, varius ut, blandit non, interdum in, ante. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Duis faucibus accumsan odio. Curabitur convallis. Duis consequat dui nec nisi volutpat eleifend. Donec ut dolor. Morbi vel lectus in quam fringilla rhoncus.",
"category": "c7",
"startDate": { "$date": "2020-04-16T01:30:30.000Z" }
}
]
I would like to filter the by month.
So far I have this in my contoller:
exports.getAllWorkouts = async (req, res, next) => {
const { startDate, category } = req.query;
try {
const page = parseInt(req.query.page) || 1;
let workouts = await Workout.find();
let filtered = await Workout.find({ category });
const pageSize = 20;
let pager = paginate(workouts.length, page, pageSize);
// get page of workouts from items array
let pageOfItems = workouts.slice(pager.startIndex, pager.endIndex + 1);
// FILTER BY CATEGORY LOGIC
if (category) {
pageOfItems = filtered.slice(pager.startIndex, pager.endIndex + 1);
pager = paginate(filtered.length, page, pageSize);
return res.json({ pager, pageOfItems });
}
// FILTER BY DATE LOGIC
if (startDate !== undefined) {
pageOfItems = await Workout.find({ startDate });
return res.json({ pager, pageOfItems });
} else {
return res.json({ pager, pageOfItems });
}
} catch (error) {
console.log(error);
}
};
I use Redux with axios on the client side to make API calls. It looks like this:
export const getAllWorkouts = (page, limit, category, startDate) => async (dispatch) => {
try {
const res = await axios.get(
`/api/v1/workout?&page=${page}&limit=${limit}&category=${category}&startDate=${moment(
startDate
)}`
);
dispatch({
type: GET_ALL_WORKOUTS,
payload: res.data,
});
} catch (error) {
console.log(error);
}
};
I use React-DateTime. When I choose a new date:
It selects the day after
When I console.log the request it shows always the today's date.
I can make successful calls in Postman.
Any help would be appreciated.
From the frontend you are sending date/time as local time zone and in the server you are using UTC format, hence the issue.
So convert the date/time to utc before sending it to the server.
export const getAllWorkouts = (page, limit, category, startDate) => async (dispatch) => {
try {
startDate = new Date(startDate).toISOString(); //<----like this
const res = await axios.get(
`/api/v1/workout?&page=${page}&limit=${limit}&category=${category}&startDate=${moment(
startDate
)}`
);
...
See a demo here
Side note - there is a prop called utc in react-datetime, see if you can make use of it.

Can we add text field dynamically

I've created an adaptive card(using json) in my chatbot that takes input from users. I want to add a button that enables the user to add a new text field every time the user clicks on the insert field. (i.e., the user can click on insert button to enter details of education (school, college etc.))
Can this be achieved in adaptive cards?
I also wanted to know, can adaptive cards be designed in any other language (excluding json)
The easiest way to do this is with Action.ShowCard:
{
"type": "AdaptiveCard",
"body": [
{
"type": "Input.Text",
"placeholder": "Placeholder 1",
"id": "text1"
}
],
"actions": [
{
"type": "Action.ShowCard",
"title": "Add field",
"card": {
"type": "AdaptiveCard",
"body": [
{
"type": "Input.Text",
"placeholder": "Placeholder 2",
"id": "text2"
}
],
"actions": [
{
"type": "Action.ShowCard",
"title": "Add field",
"card": {
"type": "AdaptiveCard",
"body": [
{
"type": "Input.Text",
"placeholder": "Placeholder 3",
"id": "text3"
}
],
"actions": [
{
"type": "Action.ShowCard",
"title": "Add field",
"card": {
"type": "AdaptiveCard",
"body": [
{
"type": "Input.Text",
"placeholder": "Placeholder 4",
"id": "text4"
}
],
"$schema": "http://adaptivecards.io/schemas/adaptive-card.json"
}
}
],
"$schema": "http://adaptivecards.io/schemas/adaptive-card.json"
}
}
],
"$schema": "http://adaptivecards.io/schemas/adaptive-card.json"
}
}
],
"$schema": "http://adaptivecards.io/schemas/adaptive-card.json",
"version": "1.0"
}
You may not like the way that looks, but there is an alternative. Microsoft Teams allows you to update messages, so you can update the card with more input fields in response to a submit action. First, you'll need a way of saving state for your card so you can update the card's activity. In C# you can declare a state property accessor like this:
public IStatePropertyAccessor<Dictionary<string, (string ActivityId, int InputCount)>> InputCardStateAccessor { get; internal set; }
Then you can instantiate it like this:
InputCardStateAccessor = _conversationState.CreateProperty<Dictionary<string, (string, int)>>("cardState");
In Node.js you won't need to declare anything but you can instantiate it like this:
this.inputCardState = this.conversationState.createProperty('cardState');
You'll want a consistent way to generate your card that you can use when you send the card initially and when you update the card. I'm using the AdaptiveCards NuGet package in C#:
public static IActivity GenerateAdaptiveCardActivityWithInputs(int inputCount, object valueObject)
{
var cardData = JObject.FromObject(valueObject);
var cardId = Convert.ToString(cardData[KEYCARDID]);
var card = new AdaptiveCard(new AdaptiveSchemaVersion(1, 0))
{
Body = Enumerable.Range(0, inputCount).Select(i =>
{
var inputId = $"text{i}";
return new AdaptiveTextInput
{
Id = inputId,
Value = Convert.ToString(cardData[inputId]),
};
}).ToList<AdaptiveElement>(),
Actions = new List<AdaptiveAction>
{
new AdaptiveSubmitAction
{
Title = "Add field",
Data = new Dictionary<string, string>
{
{ KEYCARDID, cardId },
{ KEYSUBMITACTIONID, ACTIONSUBMITADDFIELD },
},
},
new AdaptiveSubmitAction
{
Title = "Submit",
},
},
};
return MessageFactory.Attachment(new Attachment(AdaptiveCard.ContentType, content: JObject.FromObject(card)));
}
Node.js:
generateAdaptiveCardActivityWithInputs(inputCount, cardData) {
var cardId = cardData[KEYCARDID];
var body = [];
for (let i = 0; i < inputCount; i++) {
var inputId = `text${i}`;
body.push({
type: "Input.Text",
id: inputId,
value: cardData[inputId]
});
}
var card = {
type: "AdaptiveCard",
$schema: "http://adaptivecards.io/schemas/adaptive-card.json",
version: "1.0",
body,
actions: [
{
type: "Action.Submit",
title: "Add field",
data: {
[KEYCARDID]: cardId,
[KEYSUBMITACTIONID]: ACTIONSUBMITADDFIELD
},
},
{
type: "Action.Submit",
title: "Submit",
}
]
};
return MessageFactory.attachment(CardFactory.adaptiveCard(card));
}
Using this function, you can send the card initially like this in C#:
var inputCount = 1;
var cardId = Guid.NewGuid().ToString();
var reply = GenerateAdaptiveCardActivityWithInputs(inputCount, new Dictionary<string, string> { { KEYCARDID, cardId } });
var response = await turnContext.SendActivityAsync(reply, cancellationToken);
var dict = await InputCardStateAccessor.GetAsync(turnContext, () => new Dictionary<string, (string, int)>(), cancellationToken);
dict[cardId] = (response.Id, inputCount);
Node.js:
var inputCount = 1;
var cardId = Date.now().toString();
var reply = this.generateAdaptiveCardActivityWithInputs(inputCount, { [KEYCARDID]: cardId });
var response = await turnContext.sendActivity(reply);
var dict = await this.inputCardState.get(turnContext, {});
dict[cardId] = {
activityId: response.id,
inputCount: inputCount
};
await this.inputCardState.set(turnContext, dict);
And you can update the card in response to the card's "add field" submit action like this in C#:
private async Task AddFieldAsync(ITurnContext turnContext, CancellationToken cancellationToken)
{
var activity = turnContext.Activity;
if (activity.ChannelId == Channels.Msteams)
{
var value = JObject.FromObject(activity.Value);
var cardId = Convert.ToString(value[KEYCARDID]);
var dict = await InputCardStateAccessor.GetAsync(turnContext, () => new Dictionary<string, (string, int)>(), cancellationToken);
if (dict.TryGetValue(cardId, out var cardInfo))
{
var update = GenerateAdaptiveCardActivityWithInputs(++cardInfo.InputCount, value);
update.Id = cardInfo.ActivityId;
update.Conversation = activity.Conversation;
await turnContext.UpdateActivityAsync(update, cancellationToken);
dict[cardId] = cardInfo;
}
}
}
Node.js:
async addField(turnContext) {
var activity = turnContext.activity;
if (activity.channelId == 'msteams') {
var value = activity.value;
var cardId = value[KEYCARDID];
var dict = await this.inputCardState.get(turnContext, {});
var cardInfo = dict[cardId];
if (cardInfo) {
var update = this.generateAdaptiveCardActivityWithInputs(++cardInfo.inputCount, value);
update.id = cardInfo.activityId;
update.conversation = activity.conversation;
update.serviceUrl = activity.serviceUrl;
dict[cardId] = cardInfo;
await this.inputCardState.set(turnContext, dict);
await turnContext.updateActivity(update);
}
}
}
yes this is possible you can look about the addRow in javascript

How to add Virtual field after querying another Model

I want the commentCount field to show whenever i am accessing the Image model. Here is the code:
imageSchema
.virtual('commentCount')
.get(async function () {
const image_id = this._id;
const commentCount = await Comment.count({ image_id });
return commentCount;
});
In the final output for the image, I get:
{ uploaded: 2018-05-04T09:24:46.063Z,
_id: 5aec26ed56d4491ef4b3d15a,
title: 'Another snake',
description: 'Lorem ipsum dolor sit, amet consectetur adipisicing elit. Exercitationem ipsa autem culpa ea enim itaque, illo inventore obcaecati commodi minus?',
photo: '4a0831c2-f8d0-459d-ab06-794ee26c6c87.jpeg',
__v: 0,
commentCount: Promise { <pending> },
id: '5aec26ed56d4491ef4b3d15a' } ]
commentCount is a promise, even after i await the Promise. How can i resolve this issue?
Please try this while creating the schema itself:
var imageSchema= new Schema({
commentCount : {type: mongoose.Schema.Types.count, ref: 'Comment'},
pid: String,
oFile: String
});

MapReduce specific Collection using MongoDB & Mongoose

In Mongoose, using Find I am able to do something like bellow.
var activeUserQuests = ['51a02dade4b02780aeee5ab7', '51a0a40ce4b0cbb4519a8f69'];
Quest.find({_id: { $in: activeUserQuests} }, function(err, doc){
callback(doc);
});
What I'd like to do, is to do something similar, however go through a MapReduce function. Currently I have the following.
var o = {};
o.map = function() {
emit(this.problem.id, {problem:this.problem.title,quest:
{
title:this.title,
created_date: this.created_date,
updated_date: this.updated_date,
author: this.author,
description: this.description
}
});
}
o.reduce = function(previous, current) {
var array = [];
var res = {quests:array};
current.forEach(function (v) {
res.quests.push(v);
});
return res;
}
And calling the method like this
findAll: function(callback){
Quest.mapReduce(o, function(error, model, stats) {
callback(model);
});
}
My JSON looks like this:
[
{
"_id": "51a02dade4b02780aeee5ab7",
"title": "Foo",
"created_date": 2342423423423,
"updated_date": 23424234234233
},
///This one should not show up...
{
"_id": "99s8d7f9sdf79d9f7ds8f7",
"title": "Bar",
"created_date": 2342423423423,
"updated_date": 23424234234233
},
{
"_id": "51a0a40ce4b0cbb4519a8f69",
"title": "Bazz",
"author": "sdfsdfsf",
"created_date": 2342423423423,
"updated_date": 2342423423423,
"description": "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua."
}
]
This works great, however I'd like to only show items that are fed through an array, as I did with the find(). Essentially, all I want to do is...based on an arbitrary number of items and producers, only show and group my own. I am assuming that by providing a list of IDs, I might speed up the return, in the event that there are a lot of items.
What i was looking for was
o.query = {_id: { $in: activeUserQuests} }
similar code block
findTimelineByQuery: function (query, fields, options, callback) {
var obj = {};
obj.map = function() {
emit(Date.UTC(this.created.getFullYear(), this.created.getMonth(), this.created.getDate()), {
created:this.created,
title:this.title,
type: this.type,
id: this._id,
owner: this.owner,
value: this.value
});
};
obj.reduce = function(previous, current) {
var array = [];
var res = {items:array};
current.forEach(function (v) {
res.items.push(v);
});
return res;
};
obj.verbose = true;
obj.query = query;
_Items.mapReduce(obj, function(error, model, stats) {
callback(model);
});
},
I missed the "Other options:" section here http://mongoosejs.com/docs/api.html#model_Model.mapReduce

Resources