簡體   English   中英

使用 mongoose 將字符串數組推送到 mongoDB

[英]push array of strings to mongoDB with mongoose

我不確定如何使用 mongoose 將輸入字段中的字符串數組保存到 mongoDB。

理想情況下,我想在創建數組的同一輸入字段中多次輸入文本。 所以我最終會有這樣的事情。

標題:“這是我的標題”

動作:[“走路”、“微笑”、“大笑”]

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> 

博客.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;

應用程序.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)
  })
})

有關如何處理此問題的任何指南? 現在我唯一的解決方案是創建多個輸入字段,但這是不正確的。

如果actions標簽是預定義的和特定的,您可以使用 html select multiple。 這樣操作屬性將作為字符串數組發送

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

在控制器內部,您以這種方式處理

  // 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)
  })

在任何情況下,如果您想使用文本輸入來編寫由空格或逗號分隔的操作,則操作屬性將作為字符串發送。 然后您可以將字符串轉換為控制器內的數組。

// 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

無論您選擇做什么,操作都將作為字符串數組存儲在數據庫中。

可能您將數組作為字符串發送到 mongo。 您可以通過檢查 req.body.tags 的類型來檢查這一點,如下所示:

console.log(typeof req.body.tags)

如果這返回一個字符串,請確保將內容作為 JSON 發送到數據庫。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM