簡體   English   中英

如何使用 Node.js 中的 mongoose 將大數組保存到 MongoDB

[英]How to save a large array to MongoDB using mongoose in Node.js

我想在 MongoDB 中保存一個非常大的數組(超過 40k 個字符串)。

const allWords = require("an-array-of-english-words");
const { patterns } = require("./models/pattern");
const mongoose = require("mongoose");

// Create a model for the Words object
const Words = mongoose.model(
  "Words",
  new mongoose.Schema({
    words: {
      type: Array,
      required: true,
    },
  })
);

/*
  Filters the list of words to use only words greater than 4 and less than 6
*/
const array = allWords.filter(function (text) {
  return text.length >= 4 && text.length <= 6;
});

let words = [...array];
for (let i = 0; i < array.length; i++) {
  for (let j = 0; j < patterns.length; j++) {
    let result = patterns[j].test(array[i]);
    if (result) {
      let index = array.indexOf(array[i]);
      array.splice(index, 1);
    }
  }
}

async function saveWords(words) {
  console.log("start");
  const array = new Words({ words });
  console.log("mid");
  console.log(array);

  //it's successfully making the array object but it's having trouble saving it

  await array.save();
  console.log("done");
}

saveWords(words);

console.log("array length: " + array.length + " " + allWords.length);

一切正常,直到調用保存數組,然后在控制台上記錄超時錯誤。 這是我使用 Node.js 進行的第一個項目,我確信我犯了一個容易修復的小錯誤,但我不確定它是什么。

我會說您不需要將這些單詞保存在數據庫中,而是先創建一個創建隨機字符串的算法,然后如果您想添加數字或特殊字符,您可以為創建的字符串添加隨機性。

您可以使用第三方 npm package。 你可以檢查這個

此外,如果您看看其他人如何實現它,那將是一件好事。 這將是改進如何有效實施它的好習慣。 可以是一個很好的 package。

暫無
暫無

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

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