gpt4 book ai didi

javascript - 使用 mongoDB 处理用户事件源

转载 作者:行者123 更新时间:2023-12-03 09:06:05 25 4
gpt4 key购买 nike

我有一个 activityFeeds 集合,其中每个文档的主键与其引用的用户 _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);,并将每个 getTimeKey(date) 替换为 timeKey,它可以将其插入数据库中,但属性键将为“timeKey”。目前,由于意外的括号,它引发了 Meteor 构建错误。

有人遇到过这个问题吗?

最佳答案

JavaSript 在“对象表示法”中使用时“字符串化”“键”侧的所有内容。因此,使用“数组表示法”从代码中动态设置键:

var query = {_id: uid},
projection = { "fields": {} };

projection["fields"][getTimeKey(date)] = 1;

var feed = ActivityFeeds.findOne(query, projection);

这使得本例中的“投影”对象看起来像:

{ "fields": { "7_2014": 1 } }

这就是您想要的结果。

关于javascript - 使用 mongoDB 处理用户事件源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32182811/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com