【问题标题】:mongoose - trying to save an array of documents, only empty array saved猫鼬 - 试图保存一个文档数组,只保存了空数组
【发布时间】:2021-03-20 01:33:53
【问题描述】:

我有一个这样定义的架构

var PersonelModelSchema = new Schema({
  emailAddress: String,
  fullName: String
});

var ModuleModelSchema = new Schema({
  modName: String,
  personels:[PersonelModelSchema ]
});


var ModulesModelSchema=new Schema({
  modules: [ModuleModelSchema ]
});

var ModulesModel = mongoose.model('ModulesModel ', ModulesModelSchema );

此架构用于将另一个应用程序发送的数据保存到基于 nodejs 构建的 api 端点

json 数据包含一个数组,我想将其内容保存为单独的文档 - 即该数组有 2 个对象,每个对象都需要保存为单独的文档。这就是我使用数组 if ModuleModelSchema 的原因,以便我可以获取数组中的所有对象。

发布的数据是这样的

{"modfulldata" :[{
  "modName": "example-45435q5",
  personels: [
    {
      "emailAddress": "name@example",
      "fullName": "name"
    },
    {
      "emailAddress": "name2@example",
      "fullName": "name2"
    }
  ]
},
{
  "modName": "example-f45b",
  personels: [
    {
      "emailAddress": "name3@example",
      "fullName": "name3"
    },
    {
      "emailAddress": "name4@example",
      "fullName": "name4"
    }
  
  ]
}
]}

这是我用来保存的代码

app.post('/savemd', 
    function(req,res){
        console.log(req.body.modfulldata);// the data is shown correctly here

        mongoose.connect(uri, { useNewUrlParser: true, useUnifiedTopology: true, useFindAndModify: false, useCreateIndex: true });
        var db = mongoose.connection;
        db.on('error', console.error.bind(console, 'connection error:'));
        db.once('open', function callback () {
            console.log("open");          

        });

        var newmods=new ModulesModel (req.body.modfulldata);
        
    ModulesModel.insertMany(newmods).then(function(){
                db.close();
        });

    });

没有抛出任何错误。使用 console.log 语句,我可以看到请求 json 数据被正确读取。 但是在mongodb中,保存的文档中只有一个空数组

我做错了什么?

如何正确保存数据?

【问题讨论】:

  • 可能,它在某种程度上与 _id 字段(以及它的生成)相关,用于在数组中嵌入文档。 Mongoose 不会返回错误,因为文档已成功保存。此外,如果您将来尝试工作和update the array field via .save() method,您可能会发现这个关于我的 ar 的答案很有用。

标签: node.js mongodb mongoose


【解决方案1】:

这里的问题是body.modfulldata 是一个数组,您根本不能像这样创建猫鼬模式对象,而是迭代数组并生成猫鼬模式对象然后插入它们。示例:

const newmods = req.body.modfulldata.map(dataObj => {
                  return new ModulesModel(dataObj);
                });
await ModuleModel.insertMany(newmods);

【讨论】:

  • 我收到一个错误 ModuleModel.insert is not a function
  • 没关系,现在工作。使用“insertMany”而不是“insert”。在您的答案中使用“插入”的任何具体原因?
  • Hey maX,对不起,这是一个错误,正在修复中。
猜你喜欢
  • 1970-01-01
  • 2020-07-27
  • 2018-11-29
  • 2016-01-24
  • 2018-07-12
  • 2021-01-30
  • 1970-01-01
  • 2013-01-23
  • 2017-04-27
相关资源
最近更新 更多