Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
58 views
in Technique[技术] by (71.8m points)

javascript - Issue with checking and adding document item to collection in MongoDB

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:

  1. If there is no hashtag storaged in DB, it created and add all hashtags to video successfully
  2. If hashtags is already in DB, it added video successfully
  3. 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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

you need to know what is function return...

export const addHashtagToVideo = async (hashtagArr, videoObj) => {
  const waitAllDone = hashtagArr.map(async tag => { // tag in hashtagArr
    const doc = await addNewHashtagToDB(tag) // find it or create it
    return doc.id
  })

  const ary = await Promise.all(waitAllDone) // [id1, id2]
  videoObj.hashtag = ary
  // return videoObj
}

export const addNewHashtagToDB = async tag => {
  const name = tag.toLowerCase()  // whatever tag is, fix it
  let doc = await Hashtag.findOne({ name }).exec() // try to find it
  if (!doc) {
    // not exist
    doc = new Hashtag({ name }) // create new doc
    await doc.save()
  }
  return doc
}

another version

export const addHashtagToVideo = async (hashtagArr, videoObj) => {
  const waitAllDone = hashtagArr.map(addNewHashtagToDB) // amazing

  const ary = await Promise.all(waitAllDone) // [id1, id2]
  videoObj.hashtag = ary // replace it to prevent duplicat
  // return videoObj
}

export const addNewHashtagToDB = async tag => {
  const name = tag.toLowerCase()  // whatever tag is, fix it
  let doc = await Hashtag.findOne({ name }).exec() // try to find it
  if (!doc) {
    // not exist
    doc = new Hashtag({ name }) // create new doc
    await doc.save()
  }
  return doc.id // return it here
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...