我有一个架构 -
"Hello World"
在我的路线中 -
var PostSchema = new mongoose.Schema({
title: String,
link: String,
author: {type:String,required:true},
upvotes: {type: Number, default: 0},
comments: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Comment' }]
});
PostSchema.pre('validate',function(next){
console.log("Pre validate document printing - ");
console.log(this);
console.log("Pre validate called. Title : ",this._id);
console.log("Author is : ",this.author);
console.log("hasOwnProperty : ",this.hasOwnProperty("author"));
console.log("this.author==\'\' : ",this.author=='');
if(!(this.hasOwnProperty("author"))||this.author==''){
console.log("Here");
this.author="Hacked";
}
next();
});
Nodejs日志 - 打印 -
router.post('/posts', auth,function(req, res, next){
console.log(req.body);
console.log("Before - ");
var post = new Post(req.body);
post.upvotes="2";
console.log(post);
post.author="Meseeks";
console.log("After - ");
console.log(post);
console.log("Creating author");
//post.author = req.payload.username;
post.save(function(err, post){
if(err){return next(err);}
res.json(post);
});
});
我正在手动将作者设置到我的路由器中。然而,pre init功能无法验证属性" author"存在于对象中。这怎么可能?我做错了吗?
如何检查pre init中是否存在该属性?