node.js Mongoose - 保存字符串数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35509611/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 19:56:43  来源:igfitidea点击:

Mongoose - Save array of strings

node.jsmongodbexpressmongoose

提问by userMod2

I can't save an array of strings into my DB using Mongoose.

我无法使用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:

所以使用 Postman 我在正文中发送一个数组 - 但是每次我检查数据库时,它只显示一个包含整个数组的条目,即我是如何发送它的:

enter image description here

在此处输入图片说明

Any ideas what extra I'm supposed to do?

任何想法我应该做什么额外的?

回答by Ash

Write up from my comment:

从我的评论中写下:

The way to specify an array of strings in mongoose is like so:

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

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.tagslike so:

但是,这里的问题最有可能与 Postman 相关,因为它将“数组”作为字符串发送。您可以通过检查req.body.tags像这样的类型来检查这一点:

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 thisscreenshot rather than the default 'form-data' option.

如果这返回一个字符串,请确保将 Postman 中的内容类型设置为 JSON,如此屏幕截图所示,而不是默认的“表单数据”选项。

回答by Phonix

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);

回答by Gurbakhshish Singh

Try changing the schema to

尝试将架构更改为

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

or you can use Mixed type

或者你可以使用混合类型

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

EDIT

编辑

i think the problem is with assignment. Use:

我认为问题出在分配上。用:

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

回答by Harikrishna R

Firstly, as many people have noted, the schema needs to change to indicate that the tagsfield is intended to hold an array of strings, and not just a single one. So that needs to change to:

首先,正如许多人所指出的,模式需要更改以表明该tags字段旨在保存一个字符串数组,而不仅仅是一个字符串。所以需要改为:

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

The other thing you need to keep in mind (and which caused me a lot of trouble), is that when saving, make sure to use a fresh array for the tagsfield. For example, this won'twork:

您需要记住的另一件事(这给我带来了很多麻烦)是,在保存时,请确保为该tags字段使用一个新数组。例如,这将无法正常工作:

person.tags[0] = "new tag";
person.save();

Instead, you need to do something like:

相反,您需要执行以下操作:

person.tags = person.tags.slice(); // Clone the tags array
person.tags[0] = "new tag";
person.save();

Hope this helps.

希望这可以帮助。

回答by Sigkill9

Define a Schema:

定义架构:

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

In postman add each element separately using the array syntax below

在邮递员中,使用下面的数组语法分别添加每个元素

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

Return Data:

返回数据:

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

回答by Gandalf the White

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

Use this in the schema.

在架构中使用它。

Saving the Array:

保存数组:

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
                        }

回答by UA_

  1. On Schema

    techs: Array

  2. On Postman

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

  3. On DB (MongoDB)

    "techs" : [ "epxress", "rect", "html", "css", "scss" ]

  1. 在架构上

    techs: Array

  2. 关于邮递员

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

  3. 在 DB (MongoDB) 上

    "techs" : [ "epxress", "rect", "html", "css", "scss" ]