我似乎找不到我的问题的正确答案,我已经查看了整个 stackoverflow。考虑一个 C# 中的示例代码,我试图将其移植到 nodejs + mongobd。
var messageList = new List<MessageHelper>();
foreach( MessageActivation messageToAsk in messagesToAsk )
{
var message = from m in dbContext.Messages where m.Id == messageToAsk.MessageId select m;
var jokeMessage = from m in dbContext.Messages where m.Id == messageToAsk.JokeMessageId select m;
var user = from u in dbContext.Users where u.Id == messageToAsk.SourceUserId select u;
var messageHelper = new MessageHelper();
messageHelper.AskingUserId = user.ToList()[0].Id;
messageHelper.Message = message.ToList()[0];
messageList.Add( messageHelper );
}
return messageList;
以节点的方式做到这一点的最佳方法是什么?只是一个侧节点,dbContext 将查询数据库。关键是收集所有需要的信息,将其打包,然后再发送。
谢谢
编辑:
这是我尝试过的
// collect needed info to make next queries in db
var messageIdList = new Array();
var jokeMessageIdList = new Array();
var sourceUserIdList = new Array();
for( var i=0; i < messagesToAsk.length; i++ )
{
messageIdList.push( messagesToAsk[i].MessageId );
jokeMessageIdList.push( jokeMessageId[i].JokeMessageId );
sourceUserIdList .push( jokeMessageId[i].SourceUserId );
}
// make requests to have all the data in place
var messages = App.DataModels.Messages.find( {} );
messages.where( 'MessageId' ).in( messageIdList );
messages.exec( function ( err, foundMessages )
{
var jokeMessages = App.DataModels.Messages.find( {} );
jokeMessages.where( 'JokeMessageId' ).in( jokeMessageIdList );
jokeMessages.exec( function ( err, foundJokeMessages )
{
var users = App.DataModels.Messages.find( {} );
users.where( 'SourceUserId' ).in( sourceUserIdList );
users.exec( function ( err, foundUsers )
{
var messageList = new Array(); // new List<MessageHelper>();
for( var i=0; i < messagesToAsk.length; i++ )
{
var message = null;
var jokeMessage = null;
var user = null;
// get the data
for( var j = 0; j < messages.length; j++ )
{
if( messages[j].MessageId === messagesToAsk[i].MessageId )
{
message = messages[j];
break;
}
}
for( var k = 0; k < jokeMessages.length; k++ )
{
if( jokeMessages[k].JokeMessageId === messagesToAsk[k].JokeMessageId )
{
jokeMessage = jokeMessage[k];
break;
}
}
for( var l = 0; l < users.length; l++ )
{
if ( users[l].SourceUserId === messagesToAsk[l].SourceUserId )
{
user = users[l];
break;
}
}
var messageHelper =
{
"AskingUserId" : user.Id,
"AskingUserPic" : user.HelperPhoto,
"Message" : message,
"JokeMessage" : message.Type === "1" ? jokeMessage.Content
};
messageList.Add( messageHelper );
}
responseDelegate( response, messageList );
});
});
});
我在这里为其他正在转变的人发布它。这个想法似乎是您需要在开始迭代和组装任何最终结果以发送之前收集和过滤所有数据。