简体   繁体   English

使用 mongoose 将字符串数组推送到 mongoDB

[英]push array of strings to mongoDB with mongoose

I am not sure how to go about saving an array of strings from an input field to mongoDB with mongoose.我不确定如何使用 mongoose 将输入字段中的字符串数组保存到 mongoDB。

Ideally I would like to enter text several times in the same input field that creates an array.理想情况下,我想在创建数组的同一输入字段中多次输入文本。 So I would end up having something like this.所以我最终会有这样的事情。

title: "This is my Title"标题:“这是我的标题”

actions: [ "walking", "smiling", "laughing"]动作:[“走路”、“微笑”、“大笑”]

EJS File: EJS文件:

<form action="/blogs" method="POST">
        <input type="text" placeholder="title" name="title" id="title" > 
        <input type="text" name="actions" id="actions" > 
    <button >submit</button>
</form> 

blog.js博客.js

const mongoose = require("mongoose");
const Schema = mongoose.Schema;

const blogSchema = new Schema(
  {
    title: {
      type: String,
      required: true,
    },
    actions: [
      {
        type: String,
      },
    ],
  },
  { timestamps: true }
);

const Blog = mongoose.model("Blog", blogSchema);
module.exports = Blog;

app.js应用程序.js

app.post('/blogs', (req, res) =>  {
  
  const blog = new Blog ({
    title: req.body.title,
    actions: req.body.tags,
  });


  blog.save()
  .then((result) => {
    res.redirect('/blogs')
    
  })
  .catch((erro) => {
    console.log(erro)
  })
})

Any guide on how to approach this?有关如何处理此问题的任何指南? Right now my only solution is to create multiple input fields, but that is not correct.现在我唯一的解决方案是创建多个输入字段,但这是不正确的。

If the actions tags are predefined and specific you can use html select multiple.如果actions标签是预定义的和特定的,您可以使用 html select multiple。 That way actions property will be sent as an array of strings这样操作属性将作为字符串数组发送

<form action="/blogs" method="POST">
        <input type="text" placeholder="title" name="title" id="title" > 
        <label for="actions">Actions:</label>
        <select name="actions" id="actions" multiple>
            <option value="walking">walking</option>
            <option value="smiling">smiling</option>
            <option value="laughing">laughing</option>
        </select>
    <button >submit</button>
</form>

And inside the controller you handle this way在控制器内部,您以这种方式处理

  // req.body.actions is already an array.
  const blog = new Blog(req.body);
  blog.save()
  .then((result) => {
    res.redirect('/blogs')
    
  })
  .catch((erro) => {
    console.log(erro)
  })

If, in any case, you want to use a text input to write the actions separated by space or comma, the actions property will be sent as a string.在任何情况下,如果您想使用文本输入来编写由空格或逗号分隔的操作,则操作属性将作为字符串发送。 Then you can convert the string to array inside the controller.然后您可以将字符串转换为控制器内的数组。

// In case of multiple spaces, replace with single space. 
// Then split string to array of strings
let actions = req.body.actions.replace(/ +/g, " ").split(" ")

const blog = new Blog ({
    title: req.body.title,
    actions
});
// rest of code

Whatever you choose to do, the actions will be stored as array of strings in the database.无论您选择做什么,操作都将作为字符串数组存储在数据库中。

Possibly you are sending an array as a string to the mongo.可能您将数组作为字符串发送到 mongo。 You can check this by checking the type of req.body.tags like so:您可以通过检查 req.body.tags 的类型来检查这一点,如下所示:

console.log(typeof req.body.tags)

If this returns a String, make sure you send the content as JSON to the database.如果这返回一个字符串,请确保将内容作为 JSON 发送到数据库。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM