【问题标题】:Issue with checking and adding document item to collection in MongoDB在 MongoDB 中检查并将文档项添加到集合的问题
【发布时间】:2021-04-28 15:02:14
【问题描述】:

我是 Nodejs 的新手,我正在尝试使用标签创建视频。数据库中已经存储了标签,以及用户将创建的标签(将在提交视频时添加)。

例如,我添加了 2 个以上的标签,下面的代码适用于 2 种情况:

  1. 如果数据库中没有存储主题标签,则成功创建并将所有主题标签添加到视频中
  2. 如果标签已经在数据库中,则添加视频成功
  3. 但是当数据库中已经有一些主题标签而另一个没有时。它只为视频添加了几个主题标签,而不是添加了所有主题标签。我不知道为什么。我想解决这个问题。

我有 2 个这样的架构:

// Video schema
const videoSchema = new mongoose.Schema({
    url: {
        type: String
    },
    hashtag: {
        type: mongoose.Schema.Types.ObjectId,
        required: true,
        ref: 'Hashtag'
    }
})

// Hashtag schema
const hashtagSchema = new mongoose.Schema({
    name: {
        type: String,
        required: true,
        trim: true,
    }
})

用户将像这样在服务器上发布。在此示例中,Tag-In-DB-Already is in DB already 并且 New-Tag 由用户键入

{
    "url": "https://youtube.com/JvDAQD4",
    "hashtag": ["Tag-In-DB-Already", "New-Tag"]
}

像这样的视频对象

const videoObj = new Video({
                url: data.URL,
                hashtag: []
})

像这样的检查代码,我需要将 ObjectId (of hashtag) 推送到上面的 hashtagArr 中。我正在检查每个主题标签,如果主题标签不在数据库中,它将添加到数据库然后推送到数组。如果标签在数据库中,它也会添加到数组中。我希望添加用户提交的所有主题标签。

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
}

感谢您的帮助

【问题讨论】:

    标签: javascript node.js database mongodb mongoose


    【解决方案1】:

    你需要知道什么是函数返回...

    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
    }
    

    另一个版本

    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
    }
    

    【讨论】:

      猜你喜欢
      • 2021-02-26
      • 1970-01-01
      • 2017-07-13
      • 2021-10-17
      • 1970-01-01
      • 2021-10-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多