使用NodeJ多次将相同的记录插入Mongo数据库



我想实现函数性,在这里,前端的用户写下他想在数据库中插入的帖子数量。。他能写1、5、10、15,。。多达50个相同的帖子。

然后,这些帖子在数据库中是相同的,只是这个手动生成的_id不同。

一开始我以为可以这样做:

exports.addPost = async (req: any, res: any) => {
try {
const newPost = new Post({
title: req.body.title,
description: req.body.description,
author: req.body.author,
});
for (let i: number = 0; i < 5; i++) {
await newPost .save();
}
res.status(201).json(newContainer);
} catch (err) {
res.status(400).json(err);
}
};

后架构:

const PostSchema = new mongoose.Schema({
title: { type: String, required: true },
description: { type: String, required: true },
author: {
type: Schema.Authors.ObjectId,
ref: "Authors",
required: true,
},
});
module.exports = mongoose.model("Posts", PostSchema);

但我不确定,如果真的是这样的话。。对此有什么好的实践(假设循环中的数字5将出现在req.body中。因此,根据用户输入。

感谢

您只需使用以下代码:

try {
await Post.create(
new Array(5).fill(true).map((_) => ({
title: req.body.title,
description: req.body.description,
author: req.body.author,
}))
);
res.status(201).json(newContainer);
} catch (err) {
res.status(400).json(err);
}

model.create确实接受将一个(新(文档数组传递给它。通过将一个大小为5(或取决于用户输入(的新数组映射到自定义文档并将其传递给创建函数,将创建多个文档。一个巨大的好处是,您只需要执行一个数据库调用(并等待它(。

最新更新