Mongo游标更新

时间:2016-09-16 18:37:59

标签: javascript mongodb meteor

我正在使用带有Meteor / Mongo的TypeScript / Javascript。

我正在尝试更新其lastMessageCreatedAt字段上带有时间戳的游标。

  updateChat(senderId: string, chatId: string): void {

    const chatExists = !!Chats.find(chatId).count();
    if (!chatExists) throw new Meteor.Error('chat-not-exists',
      'Chat doesn\'t exist');

    const chat1 = Chats.find(chatId);
    const receiverId = chat1.memberIds.find(memberId => memberId != senderId);  // <=== error TS2339: Property 'memberIds' does not exist on type 'Cursor<Chat>'.

    const chat = {
      memberIds: [senderId, receiverId],
      lastMessageCreatedAt: new Date()
    };

    Chats.update(chat);   // <=== error TS2346: Supplied parameters do not match any signature of call target.
  },

模型

  interface Chat {
    _id?: string;
    memberIds?: string[];
    title?: string;
    picture?: string;
    lastMessage?: Message;
    lastMessageCreatedAt?: Date;
    receiverComp?: Tracker.Computation;
    lastMessageComp?: Tracker.Computation;
  }

问题

但是,我得到了上述错误。如何更新光标以获得时间戳?我是Meteor / Mongo的新手,所以我可能完全错了。

2 个答案:

答案 0 :(得分:0)

更新代码不正确。它应该是这样的

var date=new Date();

Chats.update({membersIds:{$all:[senderId,receiverId]}},{$set:{lastMessageCreatedAt: date}});

有关详细信息,请参阅docs

答案 1 :(得分:0)

首先如果有一个聊天,最好使用mongo findOne(),而不是find(),特别是如果你使用的是记录_id。记住find(),或findOne()接受一个查询json对象,以及一个可选的投影(Mongo代表要返回的字段)json对象。如果省略投影,则返回所有字段。

const chatFound = Chats.findOne(
   { '_id':
    { $eq: chatId},
   });

同样,您可以使用update()或updateOne() mongo方法。只需阅读文档,因为它们略有不同,但基本上是查询,更新和&amp;选项json对象。

Chats.update(
  { '_id': 
    { $eq: chatId},
  },
  { 'memberIds': memberIds,
    'lastMessageCreatedAt': new Date()
  }
);

一个非常有用的Mongo功能,但似乎不需要你的情况,是upsert,它可以插入或更新记录....

Chats.update(
  { '_id': 
    { $eq: chatId},
  },
  { 'memberIds': memberIds,
    'lastMessageCreatedAt': new Date()
  },
  { upsert: true }
);

最后记住,您可以在编码之前使用Mongo命令行测试您的查询。从终端窗口运行Meteor Mongo。

相关问题