.save 和 .create 在同一个异步函数中

问题描述 投票:0回答:2

下面是我将数据保存在 mongodb 中的代码

const mongoose = require('mongoose')

const sampleschema = new mongoose.Schema(
    {
        name:{
            type:String
        },
        age:{
            type:Number
        }
    },
    {collection :"Sample_collection"}
)
const samplemodel = mongoose.model('sample_coll',sampleschema)


const add = async () =>
{
    const samplerecord = new samplemodel({    
        name:'FFFF',
        age:26
    })
try
{   
    await  samplerecord.save()                 // Line A
await  samplemodel.create(samplerecord)    // Line B
   
    console.log("Style")
}
catch(e)
{
    console.log("This is error",e)
}
}

现在我已经写好了 A 行和 B 行。现在,我认为应该在我的数据库中创建两条具有相同值的记录,除了不同的

_id
之外,但是我看到只创建了一条记录。为什么会这样呢?即使我更改了 A 行和 B 行的顺序,同样的问题仍然存在。仅创建一条记录的问题是什么?

node.js mongodb async-await mongoose-schema
2个回答
0
投票

awaitsamplerecord.save();它给出了保存在数据库中的数据,因为它是基于promise的,所以需要await/(then-catch)。

const mongoose = require("mongoose");

const sampleschema = new mongoose.Schema(
  {
    name: {
      type: String,
    },
    age: {
      type: Number,
    },
  },
  { collection: "Sample_collection" }
);
const samplemodel = mongoose.model("sample_coll", sampleschema);

const add = async () => {
  try {
    const samplerecord = new samplemodel({
      name: "FFFF",
      age: 26,
    });

    //.save() method returns the object that it saves in database
    let result = await samplerecord.save(); // Line A
    //.create() does not need .save() method
    await samplemodel.create(result); // Line B

    console.log("Style");
  } catch (e) {
    console.log("This is error", e);
  }
};


0
投票

数据库中仅存储一个文档的原因是,当您在此处创建模型的新实例时:

const samplerecord = new samplemodel({    
    name:'FFFF',
    age:26
});

mongoose 实际上在保存之前就为

_id
分配了一个
samplerecord
属性。这意味着当您将
samplerecord
传递给 B 行的
await samplemodel.create(samplerecord)
函数时,
ObjectId
已经存在于数据库中,因为您在 A 行的
save()
上调用了
samplerecord
方法,因此您不能两个具有相同的
_id

© www.soinside.com 2019 - 2024. All rights reserved.