【问题标题】:insert multiple records recieved from JSON into a collection using mongoose使用 mongoose 将从 JSON 接收的多条记录插入到集合中
【发布时间】:2019-04-14 03:26:38
【问题描述】:

我有一个很大的 JSON 数组,里面有很多对象。我想插入这个 JSON 并在我的数据库中为数组中的每个对象创建一个。我是 MongoDB 和 mongoose 的新手,所以我不确定这种方法。在我读过的某些地方我需要使用插入,在我读过的一些地方我需要使用 insertMany,在一些我见过的地方创建。目前没有任何效果。我正在尝试这样做(获取数据是从远程 api 获取 JSON 的私有函数):

const mongoose = require("mongoose");
require("../../models/NFTContract");
const Contract = 
mongoose.model("contracts");

let data= getData();
module.exports = app => {
app.get("/test", (req, res, next) => {
    Contract.create(contracts, (err, docs) => {
      if (err) {
        console.log("err");
      } else {
        console.log("All should be inserted");
  }
});

});

谢谢

【问题讨论】:

    标签: node.js json database mongodb mongoose


    【解决方案1】:

    阅读these docs 了解有关 insertMany 工作原理的一些说明。这是文档中的示例:

    var arr = [{ name: 'Star Wars' }, { name: 'The Empire Strikes Back' }];
    Movies.insertMany(arr, function(error, docs) {});
    

    如果你有一个 JSON,你想先解析它。假设你有这个 JSON (source):

    {"menu": {
        "header": "SVG Viewer",
        "items": [
            {"id": "Open"},
            {"id": "OpenNew", "label": "Open New"},
            null,
            {"id": "ZoomIn", "label": "Zoom In"},
            {"id": "ZoomOut", "label": "Zoom Out"},
            {"id": "OriginalView", "label": "Original View"},
            null
        ]
    }}
    

    如果你想插入项目,你会这样做:

    Items.insertMany(JSON.parse(myJson).menu.items, (error, docs) =>
      error ? console.error(error) : console.log(docs))
    

    【讨论】:

    • 为了测试,我使用了混合模式。我已经尝试过您的代码,但没有任何内容添加到集合中,也没有在控制台上收到任何类型的错误
    猜你喜欢
    • 2015-09-25
    • 2013-03-29
    • 2016-11-26
    • 2021-10-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-05
    相关资源
    最近更新 更多