【发布时间】:2013-12-31 10:08:46
【问题描述】:
我正在尝试将文档插入到相互关联的集合中:Posts、Comments 和 Categories。 Comments 和 Categories 中的每个文档都必须有一个 PostId 字段。
我创建了一个名为insertSamplePost 的方法,它应该在将文档插入Posts 后返回帖子的ID。我已将此方法调用分配给如下变量:
var postId = Meteor.call('insertSamplePost', samplePost, function(error, id) {
if (error) {
console.log(error);
} else {
return id;
}
});
但是,当我稍后尝试使用 postId 插入相关的 cmets 和类别时,它似乎未定义!有谁知道发生了什么?
这是我的完整代码:
if (Meteor.isClient) {
Template.post.events({
'click .new-sample-post' : function (e) {
var samplePost = {
title: "This is a title",
description: "This is a description"
};
// Insert image stub
var postId = Meteor.call('insertSamplePost', samplePost, function(error, id) {
if (error) {
console.log(error);
} else {
return id;
}
});
// This returned undefined. :-()
console.log(postId);
var sampleComment = {
body: "This is a comment",
postId: postId
};
var sampleCategory = {
tag: "Sample Category",
postId: postId
};
Comments.insert(sampleComment);
Categories.insert(sampleCategory);
}
});
}
// Collections
Posts = new Meteor.Collection('posts');
Comments = new Meteor.Collection('comments');
Categories = new Meteor.Collection('categories');
// Methods
Meteor.methods({
insertSamplePost: function(postAttributes) {
var post = _.extend(postAttributes, {
userId: "John Doe",
submitted: new Date().getTime()
});
return Posts.insert(post);
}
});
【问题讨论】:
标签: javascript collections meteor