Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
468 views
in Technique[技术] by (71.8m points)

node.js - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...