Home > Blockchain >  Array not passing in express to mongo
Array not passing in express to mongo

Time:03-20

I'm trying to pass an array to MongoDB using express post request.

app.post('/createGroup', (req, res) => {
    const { title, description, tenants  } = req.body;
    const group = {
        title: title,
        description: description,
        tenants: tenants,
    };
    console.log(tenants);
    const newGroup = new Group(group);
    newGroup.save();
    res.redirect('/'); });

Everything works just fine till here. if I log console.log(tenants) returns and array of ids [ 'd8ef412c-7947-4500-8e7f-73157e30961e', 'a515dfa8-a272-4d95-87d2-a1a4f22175b5' ]

But the tenants are not passed to MongoDB. Instead, I get

_id: 623639bde8f1bdfc6eab462e
title: "Nitro"
description: "Its a Group"
tenants: Array
created_at: 2022-03-19T20:14:53.268 00:00
__v: 0

Here is my Schema,

const GroupSchema = new mongoose.Schema({
    title: String,
    description: String,
    tenants: [{type: String}],
    created_at: {
        type: Date,
        default: Date.now
    }
});

The HTML form is here.

<form  action="/createGroup" method="POST">
            <div >
                <label for="title">Group Title</label>
                <input type="text"  id="title" name="title" placeholder="Group Title / Name">
            </div>
            <div >
                <label for="description">Group Description</label>
                <textarea  id="description" name="description" rows="3"
                    placeholder="Group Description"></textarea>
            </div>
            <div>
                <fieldset>
                    <legend>
                     Tenants
                    </legend>
                    <% tenants.forEach(function(tenant) { %>
                        <div >
                            <input  type="checkbox" value="<%= tenant.tenantId %>" name="tenants[]">
                            <label  for="<%= tenant.tenantId %>">
                                <%= tenant.tenantName %>
                            </label>
                        </div>
                    <% }) %>
                </fieldset>
            </div> 
            <div >
                <button type="submit" >Create Group</button>
            </div>
        </form>

CodePudding user response:

I believe the issue is in your schema, you should be defining tenants array property like this

tenants: [String]

or you can do

tenants: { type: [String] }
  • Related