【发布时间】:2016-09-09 11:31:29
【问题描述】:
我正在使用带有 SimpleSchema 和 Collection2 的流星。并做出反应。将项目插入集合时遇到错误。这是代码:
我在 recipes.js 中的集合和架构:
import { Meteor } from 'meteor/meteor';
import { Mongo } from 'meteor/mongo';
import { SimpleSchema } from 'meteor/aldeed:simple-schema';
export const Recipes = new Mongo.Collection('recipes');
Recipes.deny({
insert() { return true; },
update() { return true; },
remove() { return true; },
});
RecipeSchema = new SimpleSchema({
name: {
type: String,
},
description: {
type: String,
},
author: {
type: String,
autoValue: function() {
return Meteor.userId();
},
},
createdAt: {
type: Date,
autoValue: function() {
if(Meteor.isClient){
return this.userId;
} else if(Meteor.isServer){
return Meteor.userId();
}
},
}
});
Recipes.attachSchema(RecipeSchema);
我在 Methods.js
中的方法代码import { Meteor } from 'meteor/meteor';
import { Mongo } from 'meteor/mongo';
import { SimpleSchema } from 'meteor/aldeed:simple-schema';
import { Recipes } from './recipes.js';
Meteor.methods({
'recipes.insert'(name, desc) {
new SimpleSchema({
name: { type: String },
desc: { type: String },
}).validate({ name, desc });
Recipes.insert({
name,
description: desc,
});
}
});
在组件的 handleSubmit 方法中的文件 AddRecipeForm.jsx 中,我获取输入的值(名称和描述),然后调用 Meteor.call('recipes.insert', name, desc);。我希望字段 Author 和 CreatedBy 使用简单模式 autoValue 在服务器上自动创建。
但是当我尝试在表单中插入一些东西时总是出错:
插入失败:错误:需要作者
我尝试将此代码添加到 recipe.insert 方法中:
let newRecipe = {
name,
description: desc,
}
RecipeSchema.clean(newRecipe);
Recipes.insert(newRecipe);
但这没有用。在官方的简单模式文档中,我发现这不是必需的:
注意:Collection2 包总是在每次插入、更新或更新之前调用 clean。
我通过将optional: true 添加到我的RecipeSchema 中的Author 和CreatedAt 字段解决了这个问题。所以作者字段的代码是:
author: {
type: String,
optional: true,
autoValue: function() {
return this.userId;
},
},
但我不希望这些字段是可选的。我只想autoValue 工作,这个字段将填充正确的值。谁知道为什么会出现这个错误以及如何解决?
更新
我注意到一个重要的时刻。我在我的表格中插入了不同的接收方(我认为由于optional: true 而工作错误)。当我运行 meteor mongo > `db.recipes.findOne()' 并获得不同的食谱时,我会得到如下对象:
meteor:PRIMARY> db.recipes.findOne()
{
"_id" : "RPhPALKtC7dXdzbeF",
"name" : "Hi",
"description" : "hiodw",
"author" : null,
"createdAt" : ISODate("2016-05-12T17:57:15.585Z")
}
所以我不知道为什么,但字段 Author 和 CreatedBy 填写正确(作者:null 因为我还没有帐户系统)。但是这样一来,schema中的required和optinal是什么意思呢?我的解决方案(optional: true)正确吗?
更新 2
又一个重要时刻!我从架构中删除了 author 字段。并从createdBy 字段中删除optional:true。它有效!十分之一可选 true。我意识到实际问题出在架构的**作者字段*中。但问题是什么?
【问题讨论】:
-
默认情况下,所有键都是必需的。设置 optional: true 来改变它。
-
我已经写过我用这种方式解决了这个问题。但我不明白它的含义。
-
奇怪的情况,它甚至可以在没有可选的情况下工作:真!需要删除作者字段 - 它有效!
标签: javascript meteor meteor-collection2 simple-schema