MeteorJS 插入方法不插入
MeteorJS insert method not inserting
我正在尝试编写一个应用程序来作为学习工具进行实时消息传递。在过去的 4 个半小时里,我一直在谷歌上搜索,试图弄清楚为什么我的插入方法不起作用。它不会抛出任何错误,它只是不执行实际的插入操作。
这是它的代码:
JS 客户端:
Template.input.events({
"keypress .input": function(event, template){
if(event.which == 13){
event.preventDefault();
var user = Meteor.user();
var message = template.find(".input").value;
alert(Meteor.call("insert", user.username, message));
template.find(".input").value = "";
}
}
});
JS 服务器:
Meteor.methods({
'insert':function(username, message){
Messages.insert({
'message': message,
'user': Meteor.userId(),
'username': username,
'timestamp': new Date()
});
return "success";
},
'find': function(){
Messages.find({}, {sort: {timestamp:-1}});
}
});
HTML:
<template name="input">
<div id="input">
<input class="input" type="text" placeholder="Message..." id="message" />
</div>
</template>
我已使用控制台进行检查以确认未添加任何内容。
您的代码运行良好,项目已保存在数据库中。正如jordandan 和Michel 提到的,这可能是由您的出版物引起的。
一种简单的检查方法是记录存储的内容。添加一些日志记录。由于服务器方法始终可以访问所有集合,因此您可以看到实际存储的内容。
'insert':function(username, message){
var id = Messages.insert({
'message': message,
'user': Meteor.userId(),
'username': username,
'timestamp': new Date()
});
console.log('Inserted id: ' + id);
var insertedMessage = Messages.findOne(id);
console.log(insertedMessage);
return "success";
},
此外,作为旁注,您可能会重新考虑将用户名作为字符串发布到服务器方法,具体取决于您的目的。这很容易被客户操纵。
相反,您可以在服务器端获取用户。
Meteor.user().username
只需确保用户实际登录,或检查 Meteor.user() 是否未定义。
我正在尝试编写一个应用程序来作为学习工具进行实时消息传递。在过去的 4 个半小时里,我一直在谷歌上搜索,试图弄清楚为什么我的插入方法不起作用。它不会抛出任何错误,它只是不执行实际的插入操作。
这是它的代码: JS 客户端:
Template.input.events({
"keypress .input": function(event, template){
if(event.which == 13){
event.preventDefault();
var user = Meteor.user();
var message = template.find(".input").value;
alert(Meteor.call("insert", user.username, message));
template.find(".input").value = "";
}
}
});
JS 服务器:
Meteor.methods({
'insert':function(username, message){
Messages.insert({
'message': message,
'user': Meteor.userId(),
'username': username,
'timestamp': new Date()
});
return "success";
},
'find': function(){
Messages.find({}, {sort: {timestamp:-1}});
}
});
HTML:
<template name="input">
<div id="input">
<input class="input" type="text" placeholder="Message..." id="message" />
</div>
</template>
我已使用控制台进行检查以确认未添加任何内容。
您的代码运行良好,项目已保存在数据库中。正如jordandan 和Michel 提到的,这可能是由您的出版物引起的。
一种简单的检查方法是记录存储的内容。添加一些日志记录。由于服务器方法始终可以访问所有集合,因此您可以看到实际存储的内容。
'insert':function(username, message){
var id = Messages.insert({
'message': message,
'user': Meteor.userId(),
'username': username,
'timestamp': new Date()
});
console.log('Inserted id: ' + id);
var insertedMessage = Messages.findOne(id);
console.log(insertedMessage);
return "success";
},
此外,作为旁注,您可能会重新考虑将用户名作为字符串发布到服务器方法,具体取决于您的目的。这很容易被客户操纵。 相反,您可以在服务器端获取用户。
Meteor.user().username
只需确保用户实际登录,或检查 Meteor.user() 是否未定义。