猫鼬-保存字符串数组 [英] Mongoose - Save array of strings
问题描述
我无法使用Mongoose
将字符串数组保存到数据库中.
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
});
模式本身看起来像:
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:
有什么想法我应该做什么?
Any ideas what extra I'm supposed to do?
推荐答案
从我的评论中撰写:
用猫鼬指定字符串数组的方法如下:
The way to specify an array of strings in mongoose is like so:
var personSchema = new mongoose.Schema({
tags: [{
type: String
}]
但是,这里的问题很可能与Postman有关,因为它以字符串形式发送数组".您可以通过检查req.body.tags
的类型来进行检查,如下所示:
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)
如果此方法返回一个String,请确保将Postman中的内容类型设置为JSON,如此所示屏幕截图,而不是默认的表单数据"选项.
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.
这篇关于猫鼬-保存字符串数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!