Meteor:如何在方法中检索插入的_id?

时间:2016-05-12 18:07:05

标签: mongodb meteor methods

我有一个meteor方法来插入文档。该文档的ID用作网址扩展名。创建文档后,我也通过相同的方法发送电子邮件。在电子邮件中,我想要包含指向网址扩展名的链接。我怎么能这样做?

//create a video
Meteor.methods({
  createVideo: function(doc) {
    Videos.insert({title: doc.title, userId: this.userId, date: new Date()});

    var emailData = {
        message: "Click the link below to go to your video.",
        buttontext: "View My Video",
        buttonlink: "http://sample.com/vids/" + ???????
    },

    body = EmailGenerator.generateHtml("actionEmailTemplate", emailData);

    Meteor.call("sendMailgunEmail",
                "account@sample.com",
                "sample",
                [Meteor.user().emails[0].address],
                "Your video is live!",
                body
    );
  }
});

2 个答案:

答案 0 :(得分:3)

来自Meteor Docs:

collection.insert(doc,[callback])

  

在集合中插入文档。返回其唯一的_id。

因此,您可以通过将其存储在本地变量

中来从插入中获取_id
var videoId = Videos.insert({title: doc.title, userId: this.userId, date: new Date()});

答案 1 :(得分:2)

查看collection.insert的{​​{3}}:

  

在集合中插入文档。返回其唯一的_id。

只需将插入的返回值分配给稍后可以引用的变量:

//create a video
Meteor.methods({
  createVideo: function(doc) {
    var videoId = Videos.insert({title: doc.title, userId: this.userId, date: new Date()});

    var emailData = {
        message: "Click the link below to go to your video.",
        buttontext: "View My Video",
        buttonlink: "http://sample.com/vids/" + videoId
    },

    body = EmailGenerator.generateHtml("actionEmailTemplate", emailData);

    Meteor.call("sendMailgunEmail",
                "account@sample.com",
                "sample",
                [Meteor.user().emails[0].address],
                "Your video is live!",
                body
    );
  }
});