Reputation: 19
When i run node mongoose_sandbox.js, i get the following error:
...\node_modules\kareem\index.js:51 } else if (pre.fn.length > 0)
TypeError: Cannot read property 'length' of undefined
'use strict';
// mongoose setup
const mongoose = require('mongoose');
mongoose.connect("mongodb://localhost:27017/sandbox");
const db = mongoose.connection;
// error handling
db.on("error", (err) => {
console.error("connection error:", err)
});
db.once("open", () => {
console.log("db bağlandı, haberin olsun");
// database work
const Schema = mongoose.Schema;
const AnimalSchema = new Schema({
type: {type: String, default: "goldfish"},
size: String,
color: {type: String, default: "golden"},
mass: {type: Number, default: "0.007"},
name: {type: String, default: "Angela"}
});
AnimalSchema.pre("save"), function (next) {
if (this.mass >= 100) {
this.size = "büyük";
} else if (this.mass >=5 && this.mass < 100) {
this.size = "orta";
} else {
this.size = "küçük";
}
next();
};
const Animal = mongoose.model("Animal", AnimalSchema);
const elephant = new Animal({
type: "fil",
color: "gri",
mass: 6000,
name: "Kutay"
});
const animal = new Animal({});
const whale = new Animal({
type: "whale",
mass: 190500,
name: "Enes"
});
const animalData = [
{
type: "mouse",
color: "gray",
mass: 0.035,
name: "Marvin"
},
{
type: "nutria",
color: "brown",
mass: 6.35,
name: "Gretchen"
},
{
type: "wolf",
color: "gray",
mass: 45,
name: "Iris"
},
elephant,
animal,
whale
];
Animal.remove({}, (err) => {
if (err) console.error(err);
Animal.create(animalData, (err, animals) => {
if (err) console.error(err);
Animal.find({}, (err, animals) => {
animals.forEach((animal) => {
if (err) console.error(err);
console.log(animal.name + " the " + animal.color + " " + animal.type + " is a " + animal.size + "-sized animal.");
});
db.close(() => {
console.log("Bağlantıyı kapattım hadi..");
});
});
});
});
});
This is a Mongoose education and i'm using this locally. I expect to see pre.save method work, but i could not have the result.
Upvotes: 0
Views: 280
Reputation: 26
it's because you have your bracket in the wrong place after the word save. AnimalSchema.pre("save") it should be
AnimalSchema.pre("save", function (next) {
if (this.mass >= 100) {
this.size = "büyük";
} else if (this.mass >=5 && this.mass < 100) {
this.size = "orta";
} else {
this.size = "küçük";
}
next();
});
Upvotes: 1