下面是我将数据保存在 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 行的顺序,同样的问题仍然存在。仅创建一条记录的问题是什么?
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);
}
};
数据库中仅存储一个文档的原因是,当您在此处创建模型的新实例时:
const samplerecord = new samplemodel({
name:'FFFF',
age:26
});
mongoose 实际上在保存之前就为
_id
分配了一个 samplerecord
属性。这意味着当您将 samplerecord
传递给 B 行的 await samplemodel.create(samplerecord)
函数时,ObjectId
已经存在于数据库中,因为您在 A 行的 save()
上调用了 samplerecord
方法,因此您不能两个具有相同的_id
。