从Mongo DB中的一系列值创建多个文档

发布于 2025-02-09 06:17:57 字数 475 浏览 3 评论 0原文

我是MongoDB的新手,我知道这对许多人来说可能很愚蠢,但是有没有办法可以从一系列值中创建多个文档。我为此编写了一些代码,但是还有其他有效/较短的方法。

tags.map(async tag => {
    const tagDoc = await TagModel.create({ tag, postID })
})

标签模式 -

const tagSchema = new mongoose.Schema({
    postID: [{
        type: mongoose.Schema.Types.ObjectId,
        ref: "Post",
    }],
    tag: {
        type: String,
        required: true,
    },
}, { timestamps: true })

I'm new to MongoDB and I know this might sound silly to many but is there a way(s) where you can create multiple documents from an array of values. I have written some code for this, but is there any other efficient/shorter way of doing that.

tags.map(async tag => {
    const tagDoc = await TagModel.create({ tag, postID })
})

Tag Schema -

const tagSchema = new mongoose.Schema({
    postID: [{
        type: mongoose.Schema.Types.ObjectId,
        ref: "Post",
    }],
    tag: {
        type: String,
        required: true,
    },
}, { timestamps: true })

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

爱的故事 2025-02-16 06:17:57

案例1:在同一集合中存储标签

字符串数组

在MySQL中您必须在不同的表中存储标签,但是在MongoDB中,您可以使用相同的集合将标签存储在帖子架构中的

const postSchema = new mongoose.Schema({
    ...
    tags: {
        type: [String],
        required: true,
    }
});

:保存POST =时>

let post = new Post();
...
post.tags = req.body.tags;   // ["Tag1","hello","Testing"];
await post.save();

案例2:在不同的集合中存储标签

如果要将标签存储在不同的收集标签中,则可以使用猫鼬 insertmany()

   let tags = req.body.tags ;  // ["Tag1","hello","Testing"];
   tagsArray = tags.map((t)=> { return {postID:post._id , tag:t}});
   let tagsSaved = await Tag.insertMany(tagsArray);
   console.log('tagsSaved=',tagsSaved);

Case 1 : Storing Tags in Same Collection

in mysql you have to store tags in different table , but in mongodb you can use same collection to store tags as array of string

in your post schema :

const postSchema = new mongoose.Schema({
    ...
    tags: {
        type: [String],
        required: true,
    }
});

when saving post =>

let post = new Post();
...
post.tags = req.body.tags;   // ["Tag1","hello","Testing"];
await post.save();

Case 2 : Storing Tags in Different Collection

if you want to store tags in different collection Tag , then you can use Mongoose InsertMany()

   let tags = req.body.tags ;  // ["Tag1","hello","Testing"];
   tagsArray = tags.map((t)=> { return {postID:post._id , tag:t}});
   let tagsSaved = await Tag.insertMany(tagsArray);
   console.log('tagsSaved=',tagsSaved);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文