I'm new in Nodejs and I'm trying to create Video with hashtag. There are hashtags already storaged in DB, and hashtag that user will create (which will be added when submit video).
For example, I add more than 2 hashtags, the code below works for 2 cases:
- If there is no hashtag storaged in DB, it created and add all hashtags to video successfully
- If hashtags is already in DB, it added video successfully
- But when there are some hashtags already in DB and the other is not. It add only few hashtags to video, not all hashtags added. I don't know why. I want to fix this case.
I have 2 schemas like this:
// Video schema
const videoSchema = new mongoose.Schema({
url: {
type: String
},
hashtag: {
type: mongoose.Schema.Types.ObjectId,
required: true,
ref: 'Hashtag'
}
})
and
// Hashtag schema
const hashtagSchema = new mongoose.Schema({
name: {
type: String,
required: true,
trim: true,
}
})
User will POST like this on server. On this example, Tag-In-DB-Already is in DB already and New-Tag is typed by user
{
"url": "https://youtube.com/JvDAQD4",
"hashtag": ["Tag-In-DB-Already", "New-Tag"]
}
videoObj like this
const videoObj = new Video({
url: data.URL,
hashtag: []
})
The checking code like this, I need to push ObjectId (of hashtag) to hashtagArr above. I'm checking for each hashtag, if hashtag not in DB, it will add to DB and then push to array. If hashtag is in DB, it also added to array. I want all hashtags that user submited will be added.
export const addHashtagToVideo = async (hashtagArr, videoObj) => {
await hashtagArr.forEach(hashtagName => { // for each hashtag check
Hashtag.findOne({ name: hashtagName.toLowerCase() }, (err, resp) => {
if (err) return
if (!resp) { // if there is no hashtag in DB
addNewHashtagToDB(hashtagName) // run add new hashtag function
.then(hashtagId => { // newHashtag._id returned from below function
videoObj.hashtag.push({ _id: hashtagId })
})
} else {
videoObj.hashtag.push({ _id: resp._id }) // if found in DB, also pushed to video
}
})
})
}
export const addNewHashtagToDB = async (hashtagName) => {
const newHashtag = await new Hashtag({
name: hashtagName.toLowerCase(),
})
newHashtag.save()
return newHashtag._id
}
Thank you for help
question from:
https://stackoverflow.com/questions/65874064/issue-with-checking-and-adding-document-item-to-collection-in-mongodb 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…