userMod2 userMod2 -4 years ago 414
Node.js Question

Mongoose - Save array of strings

I'm can't seem to 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: {
//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?

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download