Reputation: 8182
I am trying to run the code from J. Wexler's book. The book is available at GitHub.
Now, I am working on 18_1,chapter 4.
I have followed all the steps in book to create User
in REPL.
const User = require
("./models/user")
user.js
"use strict";
const mongoose = require("mongoose"),
{ Schema } = mongoose,
userSchema = new Schema(
{
name: {
first: {
type: String,
trim: true
},
last: {
type: String,
trim: true
}
},
email: {
type: String,
required: true,
lowercase: true,
unique: true
},
zipCode: {
type: Number,
min: [1000, "Zip code too short"],
max: 99999
},
password: {
type: String,
required: true
},
courses: [{ type: Schema.Types.ObjectId, ref: "Course" }],
subscribedAccount: {
type: Schema.Types.ObjectId,
ref: "Subscriber"
}
},
{
timestamps: true
}
);
userSchema.virtual("fullName").get(function() {
return `${this.name.first} ${this.name.last}`;
});
module.exports = mongoose.model("User", userSchema);
The last line exports mongoose.model
Anyway
User.create({name: { first: "John" ,last : "Walker"}, email: "[email protected]", password : "piha111"}).
... then(user => firstUser = user).
... catch(error => console.log(error.message));
leads to this error
Uncaught TypeError: User.create is not a function
Althouglh Node repl,sees User as a Function
<pre>> User
<font color="#555753">{ [Function: require] resolve: { [Function: resolve] paths: [Function: paths] }, main: undefined, extensions: [Object: null prototype] { '.js': [Function (anonymous)], '.json': [Function (anonymous)],</font></pre>
> typeof(User)
'function'
Upvotes: 0
Views: 282
Reputation: 5245
Since you are using REPL
The following will get evaluated as 2 separate statements
const User = require
("./models/user")
This will assign the function require
to variable User
and just evaluate the string "./models/user"
What you supposed to do is calling require('./models.user')
and assign it to the User
variable. It should be like this
const User = require('./models/user')
Note that this behaviour will not occur if you put the same code in a javascript file and execute it. Because the whole file will be parsed at the same time, not line by line like in REPL
Upvotes: 1
Reputation: 320
instead of
User.create({name: { first: "John" ,last : "Walker"}, email: "[email protected]", password : "piha111"}).
... then(user => firstUser = user).
... catch(error => console.log(error.message));
try this one
let newUser =new User({name: { first: "John" ,last : "Walker"}, email: "[email protected]", password : "piha111"});
newUser.save((err,usr)=>{
if(err)
return err;
firstUser = usr })
Upvotes: 1