我在从上传 [] 对象中删除项目时遇到问题。
下面代表一个用户,keys[] 代表与文件上传关联的键,uploads[] 是该键下的文件。这些都是嵌入在用户模型中的文档。我现在意识到使用引用文献会更好,但我现在坚持这样做。这是我现在用来查找上传项目的函数,
______________这是我当前的职能_____________________
老实说,我正在使用异步,但我不太理解它。是否有不同的异步函数或方法可以在 mongo 中查找这些项目,效果更好? 当前问题:1)即使找到正确的项目,这也会继续循环直到结束。 2)如何删除上传的项目?
exports.getApiDelete = function (req, res, next) {
User.findById(req.user.id, function(err, user) {
if (err) return next(err);
console.log("User ID found: "+ user._id);
//loop though user keys
async.forEach(user.profile.keys, function(item, callback) {
//verify key exists
if(item.key==req.params.scriptkey){console.log("KEY FOUND")};
async.forEach(item.uploads, function(item, callback) {
//verify file exits
console.log(req.params.file_id);
if(item._id == req.params.file_id){
// DELETE FUNCTION HERE?
};
}, function(err){
console.log('Error during async lookup: '+err);
});
}, function(err){
console.log('Error during async lookup: '+err);
});
});
};
______________________________这是我的用户模型_____________________
{
"__v": 19,
"_id": {
"$oid": "53c812c4e75ab0b013f3c6bc"
},
"email": "fake@mailinator.com",
"password": "fake",
"profile": {
"gender": "",
"keys": [
{
"_id": {
"$oid": "53c8130ae75ab0b013f3c6bd"
},
"status": false,
"iteration": 0,
"created": {
"$date": "2014-07-17T18:16:42.568Z"
},
"uploads": [],
"description": "This is being run from my Windows Desktop.",
"location": "Front Row",
"name": "fake_Desktop",
"key": "80f94c80-0dde-11e4-ae14-43922f7b8f23"
},
{
"_id": {
"$oid": "53c814ade75ab0b013f3c6be"
},
"created": {
"$date": "2014-07-17T18:23:41.777Z"
},
"description": "Windows VM test.",
"iteration": 12,
"key": "7ad78410-0ddf-11e4-ae14-43922f7b8f23",
"location": "Back Right",
"name": "fake2_Desktop",
"status": false,
"uploads": [
{
"_id": {
"$oid": "53c81517e75ab0b013f3c6bf"
},
"ip": "10.0.1.156",
"fname": "hklm_1.txt",
"iteration": 1,
"created": {
"$date": "2014-07-17T18:25:27.241Z"
},
"filepath": "script_uploads/7ad78410-0ddf-11e4-ae14-43922f7b8f23_1_hklm_1.txt"
},
{
"_id": {
"$oid": "53c8151ae75ab0b013f3c6c0"
},
"ip": "10.0.1.156",
"fname": "hklm_1.txt",
"iteration": 2,
"created": {
"$date": "2014-07-17T18:25:30.634Z"
},
"filepath": "script_uploads/7ad78410-0ddf-11e4-ae14-43922f7b8f23_2_hklm_1.txt"
}
]
}
}
最佳答案
您只想从数组中删除吗?如果是,请使用
for(var i =0, j = item.uploads.length; i < j; i++) {
//verify file exits
console.log(req.params.file_id);
if(item.uploads[i]._id == req.params.file_id){
item.uploads.slice(i, 1);
};
最后使用: user.save(function(err){}); 如果您想从文件系统中删除任何内容,请使用:
fs = require('fs');
fs.unlink( FILE PATH , function(err) {
console.log(err);
});
此外,您实际上并不需要 forEach 的异步版本,因为 User.findById 本身是异步的,并且整个过程在后台进行。
This will continue looping through until the end even after it finds the correct items.
async.forEach 没有“中断”。因此,如果您不想执行不需要的过程,请像我一样使用 for 并附加一个断点。
关于javascript - 删除项目mongodb和 Node 异步,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24813992/