我是 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 })
uj5u.com熱心網友回復:
案例 1:在同一個集合中存盤標簽
在 mysql 中,您必須將標簽存盤在不同的表中,但在 mongodb 中,您可以使用相同的集合將標簽存盤為字串陣列
在您的帖子架構中:
const postSchema = new mongoose.Schema({
...
tags: {
type: [String],
required: true,
}
});
保存帖子時=>
let post = new Post();
...
post.tags = req.body.tags; // ["Tag1","hello","Testing"];
await post.save();
案例 2:將標簽存盤在不同的集合中
如果要將標簽存盤在不同的集合 Tag 中,則可以使用 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);
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/495019.html
