目前的行为是什么?
要运行脚本,我使用babel-node
,因为脚本使用es6。
Cannot read property 'Types' of undefined
authorId: { type: mongoose.Schema.Types.ObjectId, ref: 'User' },
^
如果当前行为是错误,请提供重现的步骤。 我已经定义了这样的架构:
import * as mongoose from 'mongoose';
const Schema = mongoose.Schema;
const RecipeSchema = new Schema ({
authorId: { type: mongoose.Schema.Types.ObjectId, ref: 'User' },
name: String,
description: String,
photos: [
{
name: String,
path: String,
isMain: Boolean,
alt: String
}
],
ingredients: [
{
name: String,
quantity: Number,
metricType: {
type: String,
enum: [ 'kg', 'g', 'mg', 'l', 'ml', 'unit' ],
default: 'unit'
}
}
],
preparement: String,
isForSell: { type: Boolean, required: true, default: false },
price: Number,
url: String,
portionNumber: Number,
time: Number,
grades: [
{
user: { type: mongoose.Schema.Types.ObjectId, ref: 'User' },
grade: Number,
date: Date
}
],
} );
export default mongoose.model ( 'Recipe', RecipeSchema );
并尝试使用以下函数为数据库设定种子:
async function insert_recipe () {
const user = await User.findOne ( {} );
await Recipe.create ( {
authorId: user.id,
name: 'some name',
description: 'some description',
ingredients: [
{
name: 'foo',
quantity: 12,
metricType: 'g'
},
{
name: 'bar',
quantity: 50,
metricType: 'g'
}
],
preparement: 'how to do something like this',
isForSell: false,
portionNumber: '5',
time: 20
预期的行为是什么? 它应该使用拥有配方的第一个用户ID,并在数据库上创建配方。
请提及您的node.js,mongoose和MongoDB版本。 我现在正在使用最新版本的所有版本。 (2017年9月15日)
答案 0 :(得分:0)
经过几次试验后,我发现了一个在Schema代码中稍有变化的解决方案。
import * as mongoose from 'mongoose';
import { Schema, model } from 'mongoose';
import User from '../models/user';
const RecipeSchema = new Schema ({
authorId: { type: Schema.Types.ObjectId, ref: 'User' },
name: String,
description: String,
photos: [
{
name: String,
path: String,
isMain: Boolean,
alt: String
}
],
ingredients: [
{
name: String,
quantity: Number,
metricType: {
type: String,
enum: [ 'kg', 'g', 'mg', 'l', 'ml', 'unit' ],
default: 'unit'
}
}
],
preparement: String,
isForSell: { type: Boolean, required: true, default: false },
price: Number,
url: String,
portionNumber: Number,
time: Number,
grades: [
{
user: { type: Schema.Types.ObjectId, ref: 'User' },
grade: Number,
date: Date
}
],
} );
export default model.call(require('mongoose'), 'Recipe', RecipeSchema);
所以我基本上直接导入Schema
和model
,而不是使用mongoose.Schema
或mongoose.model
。
我还必须与model
打电话,最后引用mongoose
,例如model.call(require('mongoose'), 'Recipe', RecipeSchema);
现在一切正常。
谢谢你!