从Mongo DB中的一系列值创建多个文档
我是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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
案例1:在同一集合中存储标签
字符串数组
在MySQL中您必须在不同的表中存储标签,但是在MongoDB中,您可以使用相同的集合将标签存储在帖子架构中的
:保存POST =时>
案例2:在不同的集合中存储标签
如果要将标签存储在不同的收集标签中,则可以使用猫鼬 insertmany()
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 :
when saving post =>
Case 2 : Storing Tags in Different Collection
if you want to store tags in different collection Tag , then you can use Mongoose InsertMany()