当我运行节点mongoose_sandbox.js时,出现以下错误:
... \ node_modules \ kareem \ index.js:51 }否则,如果(pre.fn.length> 0)
TypeError:无法读取未定义的属性“ length”
'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..");
});
});
});
});
});
这是猫鼬的教育,我在当地使用。我希望看到pre.save方法有效,但是我无法得到结果。
答案 0 :(得分:0)
这是因为“保存”一词之后的括号位置错误。 AnimalSchema.pre(“保存”) 应该是
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();
});