首页 > 解决方案 > 模板助手中的异常:TypeError:无法读取未定义的属性“mergedSchema”

问题描述

我是流星新手。我正在为 quickForm 使用简单的模式并收到此错误。模板助手中的异常:TypeError:无法读取未定义的属性“mergedSchema”

main.html

<template name="hello">
  <button>Click Me</button>
  <p>You've pressed the button {{counter}} times.</p>
  {{> quickForm collection="Books" id="bookUpdateForm" type="insert"}}    

</template>

main.js

import './hello.html';    
import { Books } from '../../../api/links/books.js';

 Template.hello.onCreated(function () {
     Meteor.subscribe('books');
 });

集合 JS

import SimpleSchema from 'simpl-schema';
export const Books = new Mongo.Collection("books");
const Book = new SimpleSchema({
title: {
    type: String,
    label: "Title",
    max: 200
},
author: {
    type: String,
    label: "Author"
},
copies: {
    type: SimpleSchema.Integer,
    label: "Number of copies",
    min: 0
},
lastCheckedOut: {
    type: Date,
    label: "Last date this book was checked out",
    optional: true
},
summary: {
    type: String,
    label: "Brief summary",
    optional: true,
    max: 1000
}

});

Books.attachSchema(Book);

标签: meteormeteor-autoformsimpl-schema

解决方案


有一个错字导致后续错误。你的收藏是命名的"books",但你传递"Books"给你的quickForm. 因为AutoForm找不到任何"Books"在全局范围内命名的集合,所以会抛出错误。

这种方法也假定Books在窗口范围内。

如果你是 JS 新手,那么你可以先了解一下作用域和窗口作用域:

https://developer.mozilla.org/en-US/docs/Glossary/Scope

https://developer.mozilla.org/en-US/docs/Web/API/Window

为什么全局变量被认为是不好的做法?


不易出错的模式

另一种方法是导入Books您的模板(正如您已经完成的那样)并quickForm 通过模板助手提供它:

main.html

<template name="hello">
  {{> quickForm collection=getCollection id="bookUpdateForm" type="insert"}}    
</template>

请注意getCollection,这基本上是在调用您在模板助手部分中定义的助手:

main.js

import './hello.html';    
import { Books } from '../../../api/links/books.js';

Template.hello.onCreated(function () {
    Meteor.subscribe('books');
});

Template.hello.helpers({
    getCollection() {
      return Books;
    }
});

通过这样做,您有 a) 避免了窗口(全局)范围和 b) 避免了由于拼写错误而导致的错误,因为您将对集合的引用直接传递给 quickForm。

集合 JS

import SimpleSchema from 'simpl-schema';
export const Books = new Mongo.Collection("books");
const Book = new SimpleSchema({
    title: {
        type: String,
        label: "Title",
        max: 200
    },
    author: {
        type: String,
        label: "Author"
    },
    copies: {
        type: SimpleSchema.Integer,
        label: "Number of copies",
        min: 0
    },
    lastCheckedOut: {
        type: Date,
        label: "Last date this book was checked out",
        optional: true
    },
    summary: {
        type: String,
        label: "Brief summary",
        optional: true,
        max: 1000
    }
});

Books.attachSchema(Book);

推荐阅读