简体   繁体   中英

mongoose returning ObjectParameterError() while saving to database

I have a restaurant schema and a reviews schema....whenever I am trying to include a review in the mongoose database using create() method it is generating error as:

ObjectParameterError: Parameter "obj" to Document() must be an object, got very costly place at new ObjectParameterError (/workspace/groomIDE-setup123/restaurants/node_modules/mongoose/lib/error/objectParameter.js:25:11)

my schemas are as follows:

var restSchema = new mongoose.Schema({
    title: String,
    review: String,
    image: String,
    reviews:[{
        type:mongoose.Schema.Types.ObjectId,
        ref:"Review"
    }
    ]
})
var reviewSchema = new mongoose.Schema({
    author:{
        id:{
            type:mongoose.Schema.Types.ObjectId,
            ref:"User"
        },
        username:String
    },
    review:String
});

The Route for creating a new review and displaying it is as follows:

app.post("/restaurants/:id/reviews",(req,res)=>{
    Restaurant.findById(req.params.id,(err,foundRestaurant)=>{
        if(err)
            console.log(err);
        else
        Review.create(req.body.comment,(err,newReview)=>{
        if(err)
            console.log(err);
        else{
            newReview.author.id=req.user._id;
            newReview.author.username=req.user.username;
            newReview.save();
            foundRestaurant.reviews.push(newReview);
            foundRestaurant.save();
            // res.redirect("/restaurants/"+req.params.id);
            }
        })  
    })
});
app.get("/restaurants/:id",(req,res)=>{
    Restaurant.findById(req.params.id).populate("reviews").exec((err,foundRestaurant)=>{
        if(err)
            console.log(err);
        else{
            res.render("show",{restaurant:foundRestaurant});
            }
    })
});

Mongoose create() function need to get values matching the schema. You can read more about it here : https://mongoosejs.com/docs/api.html#model_Model.create Try to define your new newReview object and then pushing it into foundRestaurant.reviews array like so:

set new review object:

const newReview={ author.id:req.user._id, username:req.user.username, };

create and save it:

Review.create(newReview);

and then push it into the Restaurant.reviews array:

foundRestaurant.reviews.push(newReview);

hopefully this makes sense

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM