我正在使用meteor与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中,我获取输入的值(name和desc),然后调用Meteor.call('recipes.insert', name, desc);
。我希望使用简单模式autoValue在服务器上自动创建字段Author和CreatedBy。
但是当我试图用表格插入某些内容时,我总是有错误:
插入失败:错误:需要作者
我尝试将此代码添加到 recipe.insert 方法:
let newRecipe = {
name,
description: desc,
}
RecipeSchema.clean(newRecipe);
Recipes.insert(newRecipe);
但那没用。在官方的简单模式文档中,我发现没有必要:
注意:Collection2包在每次插入,更新或upsert之前总是调用clean。
我在向 RecipeSchema 中的字段optional: true
和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因为我还没有帐户系统)。但是这样,架构中必需和 optinal 的含义是什么?我的解决方案(optional: true
)是否正确?
更新2
另一个重要时刻!我从架构中删除了author
字段。并从optional:true
字段中删除了createdBy
。它的工作原理! tithout可选true。我意识到实际问题出现在架构的**作者字段中。但问题是什么?
答案 0 :(得分:1)
我猜这是内部框架问题。你的第一个代码看起来非常好。您可以在aldeed:collection2 github存储库上发布此问题,而不是在此处发布此问题。维护它的有关人员将调查这个问题。