在mongo集合中找到数组的第n个元素?流星 [英] find nth element of array in mongo collection? meteor

查看:111
本文介绍了在mongo集合中找到数组的第n个元素?流星的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为ChatRooms的集合,该集合具有一个chatIds数组,它们只是聊天室中谁的用户ID。一次只有两个ID。
我想在此数组中找到第一个元素并将其设置为变量 messager,以便我可以查看它是否属于当前登录的人。否则,将添加刚刚发送的消息到另一个称为通知的集合中,以便可以通知其他用户收到消息。我一直在查询中收到语法错误,但不知道为什么。这是我的代码块:

I have a collection called ChatRooms that has an array of chatIds, which are just the user Ids of who is in the chatroom. There are only two ids in the array at a time. I want to find the first element in this array and set it to the variable "messager" so that i can see if it belongs to the person currently logged in. if not, the message that was just sent will be added to a different collection called notifications, so that the other user can be notified of receiving a message. I keep getting syntax errors on the query, and I don't know why. Here is my block of code:

createMessageNotification = function(message) {
  var messager = ChatRooms.find( {}, { chatIds: { $slice: 0,1 } } );
  //console.log(messager);

  if(messager !== Meteor.userId()){
    Notifications.insert({

      message: message.value
    });
  }
}


推荐答案

$ slice 需要标量或数组参数。 文档另外,您还应该执行 findOne 返回一个对象,而不是 find 返回一个游标。

$slice needs a scalar or an array parameter. docs Also you should be doing a findOne which returns an object instead of a find which returns a cursor.

尝试其中一个:

var messager = ChatRooms.findOne( {}, { chatIds: { $slice: 1 } } ).chatIds;

var messager = ChatRooms.findOne({}).chatIds[0];

这篇关于在mongo集合中找到数组的第n个元素?流星的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆