我有一个activityFeeds
集合,其中每个文档的主键与用户所引用的_id相同_id。
我做了一个getTimeKey函数,它根据特定的日期返回一个字符串
/*
** Return a string like 1_2015 for january 2015
** If timestamp is not defined, current date is used
*/
getTimeKey = function (timestamp)
{
var date = (timestamp === undefined ? new Date() : new Date(timestamp));
return date.getMonth().toString() + "_" + date.getYear().toString();
}
当我在JS中使用它来访问对象属性时,它很有效:
myProperty = myObj[getTimeKey()]; // get the aray of activity for the current month
问题是当我想在我的文档/集合中添加一个活动时,getTimeKey()被解释为mongo查询中的一个字符串。
/*
** Add a new activity to a user activity feed
** Get the time key from the passed date
** Returns false if a required parameter is not defined
** If the user has already an activity feed started, then check if the time key exists
** If it exists, push it the new activity, else create it
** If the user do not already have an activity feed started, then create it
**
** PARAMETERS :
** uid -> user's activity feed to update
** type -> the type of activity, see below
** data -> some specific data, see below
** date -> (optionnal) the date of the event
**
** TYPES :
** "ntt" -> data: { tId: threadId }
** "reply" -> data: { tId: threadId, pId: postId }
** "mate" -> data: { mId: mateId }
*/
addNewActivityTo = function (uid, type, data, date)
{
if (uid && type && data && timeKey)
{
var feed = ActivityFeeds.findOne({_id: uid}, {fields: {getTimeKey(date): 1}});
if (feed)
{
if (feed[getTimeKey(date)])
{
ActivityFeeds.update({_id: uid}, {
$push: { getTimeKey(date): { type: type, data: data, date: date } }
}, {multi: false});
}
else
{
ActivityFeeds.update({_id: uid}, {
$set: { getTimeKey(date): [ { type: type, data: data, date: date } ] }
}, {multi: false});
}
}
else
{
ActivityFeeds.insert({
_id: uid,
getTimeKey(date): [ { type: type, data: data, date: date } ]
});
return { type: type, data: data, date: date };
}
}
devError("Couldn't add new activity to user, parameters are missing.");
return false;
}
我想要的是能够在查询中创建所需的密钥(例如,2014年9月的7_2014)或搜索它。我如何让mongo明白他必须寻找getTimeKey()的返回而不是把它当作字符串?
如果我存储getTimeKey()返回如下:var timeKey = getTimeKey(date);
,并用timeKey替换每个getTimeKey(date),它可以将它插入数据库,但属性键将是"timeKey"
。就目前而言,由于意外的括号,它会给我一个Meteor构建错误。
有没有人遇到过这个问题?
答案 0 :(得分:0)
以下是如何使用MongoDB构建活动供稿的示例:https://github.com/GetStream/mongodb-activity-feed
数据模型MongoDB活动提要项目使用5种不同的模式: