Reputation: 1255
What is the current behavior?
To run the script, I'm using babel-node
since the script uses es6.
Cannot read property 'Types' of undefined
authorId: { type: mongoose.Schema.Types.ObjectId, ref: 'User' },
^
If the current behavior is a bug, please provide the steps to reproduce. I've defined the schema like this:
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 );
And tried to seed the database with a function like this:
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
What is the expected behavior? It should use the first user's ID that owns the recipe and create the recipe itself on the database.
Please mention your node.js, mongoose and MongoDB version. I'm using the last versions for all of them in the current moment. (2017-09-15)
Upvotes: 1
Views: 3708
Reputation: 1255
After a few trials, I found a solutions with a bit change in the Schema code.
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);
So I'm basically importing Schema
and model
directly instead of using with mongoose.Schema
or mongoose.model
.
I also had to make a call with model
in the end to reference mongoose
, like model.call(require('mongoose'), 'Recipe', RecipeSchema);
Now everything worked fine.
Thanks btw!
Upvotes: 1