簡體   English   中英

最小化長mongo語句

[英]Minimize long mongo statement

此處概述此mongo插入時間如此長且需要5次調用的原因(使用內容可尋址哈希管理數據庫) ,我希望使其更有意義/不那么冗長。 是否有我缺少的功能允許我根據值是否在數組中有條件地進行向上插入。

function insert (user, type, data, name) {
  var hash = util.getHash(data)
  var collection = db.collection('content')
  return collection.find({
    'user': user,
    'type': type,
    'hash': hash,
    'meta.name': name
  }).toArray().then(function (arr) {
    if (!arr.length) {
      return collection.find({
        'user': user,
        'type': type,
        'hash': hash
      }).toArray().then(function (arr) {
        if (!arr.length) {
          return collection.insert({
            'user': user,
            'type': type,
            'hash': hash,
            'date': new Date(),
            'data': data,
            'meta': [
              {
                'name': name
                'date': new Date()
              }
            ],
          })
        } else {
          return collection.update({
            'user': user,
            'type': type,
            'hash': hash,
            'meta.name': name
          }, {
            '$push': {
              'meta': {
                'name': name
                'date': new Date()
              }
            }
          })
        }
      })
    } else {
      return collection.update({
        'user': user,
        'type': type,
        'hash': hash,
        'meta.name': name
      }, {
        '$push': {
          'meta': {
            'date': new Date()
          }
        }
      })
    }
  })
}

這是一個電話,與它唯一的問題是,它會更新name ,每次,我想它不會更新name ,如果name中存在meta陣列。

function insert (user, type, data, name) {
  var content = {
    'user': user,
    'data': data,
    'hash': util.getHash(data),
    'date': new Date()
  }
  var collection = db.collection('contents')
  return collection.update({
    'user': content.user,
    'type': content.type
  }, {
    '$setOnInsert': content,
    '$push': {
      'meta': {
        'name': name,
        'date': new Date()
      }
    }
  }, {
    'upsert': true
  })
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM