gpt4 book ai didi

javascript - 插入 Meteor 中的集合时出错

转载 作者:行者123 更新时间:2023-12-03 06:57:36 24 4
gpt4 key购买 nike

我正在将 Meteor 与 SimpleSchema 和 Collection2 一起使用。并使用react。我在将项目插入集合时遇到错误。这是代码:

我在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 在服务器上自动创建。

但是当我尝试用表单插入某些内容时总是出现错误:

insert failed: Error: Author is required

我尝试将此代码添加到 recipe.insert 方法中:

let newRecipe = {
name,
description: desc,
}

RecipeSchema.clean(newRecipe);
Recipes.insert(newRecipe);

但这没有用。在官方简单模式文档中,我发现这是没有必要的:

NOTE: The Collection2 package always calls clean before every insert, update, or upsert.

我通过添加 optional: true 解决了这个问题到田野AuthorCreatedAt在我的RecipeSchema中。所以作者字段的代码是:

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中的requiredoptinal是什么意思呢?我的解决方案(使用 optional: true )正确吗?

更新2

又一个重要时刻!我删除了author模式中的字段。并删除 optional:true来自createdBy field 。它有效!没有可选的 true。我意识到实际问题出在模式的**作者字段*中。但问题是什么?

最佳答案

我猜这是内部框架问题。您的第一个代码看起来完全没问题。您可以将其发布到 aldeed:collection2 github 存储库,而不是在此处发布此问题。维护它的相关人员将调查这个问题。

关于javascript - 插入 Meteor 中的集合时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37207114/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com