Search code examples
node.jsmongodbexpressmongoose

Mongoose - Save array of strings


I can't save an array of strings into my DB using Mongoose.

(Note all code below is simplified for ease of writing here)

So i declare a variable of a person schema I have:

var newPerson = new Person ({
    tags: req.body.tags
});

The schema itself looks like:

var personSchema = new mongoose.Schema({
  tags: Array
});

And when it comes to saving its just a simple:

newPerson.save(function(err) {
    //basic return of json
});

So using Postman I send in an array in the body - however everytime I check the DB, it just shows one entry with the array as a whole i.e. how I sent it:

enter image description here

Any ideas what extra I'm supposed to do?


Solution

  • Write up from my comment:

    The way to specify an array of strings in mongoose is like so:

    var personSchema = new mongoose.Schema({
    tags: [{
        type: String
    }]
    

    However, the problem here is most-likely to do with Postman as it is sending the 'array' as a string. You can check this by checking the type of req.body.tags like so:

    console.log(typeof req.body.tags)
    

    If this returns a String, make sure to set the content-type in Postman to JSON as seen in this screenshot rather than the default 'form-data' option.