Javascript 最小化长mongo语句
这个mongo插入如此之长,需要5次调用的原因如下所述,我希望让它更有意义/不那么冗长。如果数组中有值,是否有一个功能允许我有条件地向上插入Javascript 最小化长mongo语句,javascript,node.js,mongodb,Javascript,Node.js,Mongodb,这个mongo插入如此之长,需要5次调用的原因如下所述,我希望让它更有意义/不那么冗长。如果数组中有值,是否有一个功能允许我有条件地向上插入 function insert (user, type, data, name) { var hash = util.getHash(data) var collection = db.collection('content') return collection.find({ 'user': user, 'type': typ
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()
}
}
})
}
})
}
这是一个调用,唯一的问题是它每次都会更新名称,如果名称存在于元数组中,我希望它不要更新名称
您可以使用一些命名函数,而不是将所有回调都定义为匿名内联函数。@bhspencer您完全正确。我真的不想一开始就有这么多调用,这段代码更多的是为了展示我在MongoDB中寻找替代方案的结果。
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
})
}