我试图写一种方式insert
和find
。我很简单,希望能够插入string
或json
之类的任何内容。我希望通过内容的哈希来查找内容,我有一个getHash()
function
,可以为内容生成哈希。
这就是我想要的:
// insert(user, dataType, data, dataName)
insert('thomasreggi', 'example', {'foo': 'bar'}, 'document.json')
// find(user, dataType, hash)
var hash = getHash({'foo': 'bar'})
find('thomasreggi', 'example', hash)
这就是我目前所拥有的:
/* global db */
function insert (user, dataType, data, dataName) {
var content = {}
content.type = dataType
content.data = data
content.name = dataName
content.hash = util.getHash(data)
content.date = new Date()
var users = db.collection('users')
return users.updateAsync({
'service.user': user
}, {
'$push': {'content': content}
}).then(function () {
return content
})
}
function find (user, dataType, dataHash) {
var users = db.collection('users')
return users.aggregateAsync(
{$match: {'service.user': user}},
{$unwind: '$content'},
{$project: {content: 1}},
{$match: {
'content.type': dataType,
'content.hash': dataHash
}},
{$sort: {'content.date': -1}},
{$limit: 1}
).then(function (content) {
if (!content || content.length === 0) return false
return content
})
}
user
集合中,是否应存储在content
集合中?hash
,这意味着如果插入了两个内容,则会重复这些内容。push
new Date
。{/ li>
push
,我想要dataName
更新名称的方法。示例:
以下代码应创建以下文档
insert('thomasreggi', 'example', {'foo': 'bar'}, 'alpha.json')
insert('thomasreggi', 'example', {'foo': 'bar'}, 'beta.json')
{
type: 'example'
data: {'foo': 'bar'}
hash: getHash({'foo': 'bar'}) // value of hash
date: [
new Date(), // first date
new Date() // second date
]
name: [
'alpha.json',
'beta.json'
]
}
但是,当应用相同的名称时,应按下第二个插入的日期。
insert('thomasreggi', 'example', {'foo': 'bar'}, 'alpha.json')
insert('thomasreggi', 'example', {'foo': 'bar'}, 'alpha.json')
{
type: 'example'
data: {'foo': 'bar'}
hash: getHash({'foo': 'bar'}) // value of hash
date: [
new Date(), // first date
new Date() // second date
]
name: [
'alpha.json'
]
}
更新
这是我第一次尝试插入功能
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()
}
}
})
}
})
}