mardi 13 décembre 2022

How to store a checkbox value as array in mongoDB with mongoose

I would like to store checkbox a value as array in mongoDB, using mongoose schema. I can get the values in array if I check more than 2 boxes. But as string when I check only one.

The following is for the checkbox in form in ejs file

<div class="mb-3">
   <div class="form-check form-check-inline">
      <input class="form-check-input" type="checkbox" id="Culture" value="Culture" name="place[categories]">
      <label class="form-check-label" for="Culture">Culture</label>
   </div>
   <div class="form-check form-check-inline">
      <input class="form-check-input" type="checkbox" id="Sport" value="Sport"  name="place[categories]">
      <label class="form-check-label" for="Sport">Sport</label>
   </div>
   <div class="form-check form-check-inline">
      <input class="form-check-input" type="checkbox" id="Nature" value="Nature"  name="place[categories]">
      <label class="form-check-label" for="Nature">Nature</label>
   </div>
    <div class="form-check form-check-inline">
      <input class="form-check-input" type="checkbox" id="Education" value="Education"  name="place[categories]">
      <label class="form-check-label" for="Education">Education</label>
   </div>
</div>

This is mongoose Schema

const mongoose = require("mongoose");

const placeSchema = new mongoose.Schema({
    title: String,
    categories: [String],
    location: String,
    description: String
})

This is backend with express, for your info.

app.get("/places/new", (req, res) => {
    res.render("places/new.ejs");
});

app.post("/places", async(req, res) => {
    const place = new Place(req.body.place);
    await place.save();
    res.redirect("/places");
});

Thank you for reading and I hope I could find solution.

I tried to change the schema design as following, but doesn't go well.

const categorySchema = new mongoose.Schema({ name: String });

const placeSchema = new mongoose.Schema({
    title: String,
    categories: [categorySchema],
    location: String, 
    description: String,
    image: String,
})



Aucun commentaire:

Enregistrer un commentaire