如何在我的expressJS应用程序中使用一个喜欢的按钮?

时间:2018-10-23 17:04:53

标签: node.js express

我正在尝试让类似的按钮在我的网站上正常工作,这是代码。[在此处输入图片描述] [1]

router.put('/campgrounds/:id/likes',isLoggedIn,function(req,res){
Campground.findById(req.params.id).populate('likes').exec(function(err,foundCampground){
    if(err){
        console.log(err);
        res.redirect('back');
    }else{
        foundCampground.likes.author.id=req.user.id;
        foundCampground.likes.username=req.user.username;
        foundCampground.likes.push(req.user.username);
        foundCampground.save();
        res.redirect('/campgrounds/' + foundCampground.id);


    }
});

});

var mongoose=require("mongoose");

var likeSchema=mongoose.Schema({
    author:{
        id:{
            type:mongoose.Schema.Types.ObjectId,
            ref:'User'
        },
        username:String
    }
});

module.exports=mongoose.model('Like',likeSchema);

var campgroundSchema=new mongoose.Schema({
name:String,
image:String,
imageId:String,
description: String,
createdAt:{type:Date,default:Date.now()},
author:{
    id:{
        type:mongoose.Schema.Types.ObjectId,
        ref: 'User'
    },
    username:String
},
comments: [{
    type:mongoose.Schema.Types.ObjectId,
    ref:'Comment'
}],
likes: [{
    type:mongoose.Schema.Types.ObjectId,
    ref:'Likes'
}]

});

module.exports = mongoose.model('Campground',campgroundSchema);

我被困在这里,请帮忙,因为我确实需要它来工作。我似乎无法在这里解决问题。

1 个答案:

答案 0 :(得分:0)

您是否要创建或更新(参考CRUD操作)?看来您正在尝试创建,因此应该使用“ post”而不是“ put”。尝试使用“ router.post”而不是“ router.put”。

router.post('/campgrounds/:id/likes',isLoggedIn,function(req,res){
Campground.findById(req.params.id).populate('likes').exec(function(err,foundCampground){
    if(err){
        console.log(err);
        res.redirect('back');
    }else{
        foundCampground.likes.author.id=req.user.id;
        foundCampground.likes.username=req.user.username;
        foundCampground.likes.push(req.user.username);
        foundCampground.save();
        res.redirect('/campgrounds/' + foundCampground.id);

       }

    });
});