Mongoose - 保存字符串数组 [英] 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
});
所以使用 Postman 我在正文中发送一个数组 - 但是每次我检查数据库时,它只显示一个包含整个数组的条目,即我如何发送它:
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?
推荐答案
根据我的评论写下来:
在 mongoose 中指定字符串数组的方式是这样的:
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)
如果这返回一个字符串,请确保将 Postman 中的内容类型设置为 JSON,如this屏幕截图而不是默认的表单数据"选项.
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.
这篇关于Mongoose - 保存字符串数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!