hasOwnProperty在Mongoose的预验证中不起作用

时间:2017-02-11 14:02:55

标签: node.js mongodb mongoose mean-stack

我有一个架构 -

"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中是否存在该属性?

1 个答案:

答案 0 :(得分:1)

代码中的那个点是"这个"不是对象,只是原型。提供了更多解释和解决方法here