Mongoose - 保存字符串数组

64

使用Mongoose,我无法将一个字符串数组保存到我的数据库中。

(注意下面的所有代码都是为了方便在此处编写而简化的)

所以我声明了一个我拥有的人物模式变量:

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

这个模式本身看起来像:

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

说到节省,只需要简单地:

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

所以我使用Postman在请求体中发送了一个数组,但是每次我检查数据库时,它只显示一个包含整个数组的条目,就像我发送的那样:

输入图像描述

有任何想法应该再做些什么吗?


3
这个可以吗?- var personSchema = new mongoose.Schema({ tags: [{type: String}] }); - Ash
那么只需要这样:var personSchema = new mongoose.Schema({ tags: [String] }); - Ash
很遗憾,这也不行。 - userMod2
1
你确定 req.body.tags 是一个数组吗?尝试执行 - console.log(typeof req.body.tags) 或者 Array.isArray(req.body.tags) - Ash
啊!- 这是一个字符串。发现得好。那么在Postman中 ['people', 'players'] 有什么问题吗? - userMod2
显示剩余3条评论
13个回答

152

以下是我的评论总结:

在mongoose中指定字符串数组的方法如下所示:

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

然而,这里的问题很可能与Postman有关,因为它将"数组"作为一个字符串发送。您可以通过检查req.body.tags的类型来验证此事:

console.log(typeof req.body.tags)

如果此操作返回一个字符串,请确保在Postman中将内容类型设置为JSON,如截图所示,而不是默认的“form-data”选项。


问题出在Postman上,它将我的数组视为字符串而非数组。 - userMod2
希望设置内容类型可以解决它。您始终可以将其填充到对象中并将其作为JSON对象发送。 - Ash
如何在数组中推送更多数据并避免重复? - huykon225

63
var schema = new Schema({
  name:    String,
  binary:  Buffer,
  living:  Boolean,
  updated: { type: Date, default: Date.now },
  age:     { type: Number, min: 18, max: 65 },
  mixed:   Schema.Types.Mixed,
  _someId: Schema.Types.ObjectId,
  decimal: Schema.Types.Decimal128,
  array: [],
  ofString: [String],
  ofNumber: [Number],
  ofDates: [Date],
  ofBuffer: [Buffer],
  ofBoolean: [Boolean],
  ofMixed: [Schema.Types.Mixed],
  ofObjectId: [Schema.Types.ObjectId],
  ofArrays: [[]],
  ofArrayOfNumbers: [[Number]],
  nested: {
    stuff: { type: String, lowercase: true, trim: true }
  },
  map: Map,
  mapOfString: {
    type: Map,
    of: String
  }
})

// example use

var Thing = mongoose.model('Thing', schema);

var m = new Thing;
m.name = 'Statue of Liberty';
m.age = 125;
m.updated = new Date;
m.binary = Buffer.alloc(0);
m.living = false;
m.mixed = { any: { thing: 'i want' } };
m.markModified('mixed');
m._someId = new mongoose.Types.ObjectId;
m.array.push(1);
m.ofString.push("strings!");
m.ofNumber.unshift(1,2,3,4);
m.ofDates.addToSet(new Date);
m.ofBuffer.pop();
m.ofMixed = [1, [], 'three', { four: 5 }];
m.nested.stuff = 'good';
m.map = new Map([['key', 'value']]);
m.save(callback);

我已经尝试了所有可能的方法,但仍然显示没有数据的数组键(空数组键)。 - AbhimanuSharma

15
  1. 关于 Schema:
    ( 鉴于问题中提到它是一个 字符串数组 )
var personSchema = new mongoose.Schema({
  tags:{
     type:[String],
     required: true
  }
}); 
  1. 在Postman上:
{
  "tags": ["css", "javascript", "mongoose", "node"]
}
  1. 关于MongoDB
{
  "tags":["css", "javascript", "mongoose", "node"]
}

同样地,您可以在mongoose模式中创建其他类型的原始数组和文档数组,如下所示:

({
  toys: [ToySchema],
  buffers: [Buffer],
  strings: [String],
  numbers: [Number]
  // ... etc
});

11

尝试更改模式为

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

或者您可以使用混合类型

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

编辑

我认为问题出在赋值上。请使用:

person.tags.push("string to push");

如果这个没有起作用,我认为问题出在其他地方,而不是模式中。 - Gurbakhshish Singh

4
  1. 关于模式

    techs: 数组

  2. 关于Postman

    "techs": ["express","react","html","css","scss"]

  3. 关于数据库(MongoDB)

    "techs" : [ "express", "react", "html", "css", "scss" ]


2

定义模式:

const schema = new Schema({
  name: { type: String, required: true },
  tags: [String]
});

在 Postman 中,使用以下数组语法单独添加每个元素

name:Thing
tags[]:task
tags[]:other
tags[]:thing

返回数据:

{
    "__v": 0,
    "name": "Thing",
    "_id": "5a96e8d0c7b7d1323c677b33",
    "tags": [
        "task",
        "other",
        "thing"
    ]
}

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

在模式中使用此代码。

保存数组:

var etc = new modename({yourprimaryid: primaryid});
                        for (var i = 0; i < tag.length; i++) {
                            etc.tag.push(tag[i]);
                        }
                        etc.save(function(err) {
                          //whatever you want here
                        }

感谢 @Siddharth Ajmera - Gandalf the White
@userMod2 如果情况需要,请发布其他代码,因为模式问题不应该存在。我实际上使用的是Express Mongoose(Mongo),并且我已经使用了类似的系统。 - Gandalf the White
我只是在这里复制了一些我的代码,但我不得不编辑其中的大部分。请检查一下是否适用于您。 - Gandalf the White

2
我有一个类似的问题, 在模型中,做如下操作:

tags : {[String], default: undefined}

所以它默认为未定义而不是空数组,而不是这样:

const person = new Person({
    tags : req.body.tags
});

做这个:
const person = new Person();
person.tags = req.body.tags;

2

我的需求: 成分:字符串类型的数组

解决方案:

ingredients: {
    type: [String],
  },

2

这也可以工作

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接