Node.js 在nodejs中递归收集数据,然后逐个删除
infom_col是一个集合,其中包含一个字段rkey,该字段本身包含一个如下数组:rkey->brands,所以brands是一个ID数组。这些ID引用集合中的其他文档。我需要收集所有这些依赖ID并逐个删除文档 这是我的密码。引发错误:TypeError:无法读取未定义的属性“rkeys”Node.js 在nodejs中递归收集数据,然后逐个删除,node.js,mongojs,Node.js,Mongojs,infom_col是一个集合,其中包含一个字段rkey,该字段本身包含一个如下数组:rkey->brands,所以brands是一个ID数组。这些ID引用集合中的其他文档。我需要收集所有这些依赖ID并逐个删除文档 这是我的密码。引发错误:TypeError:无法读取未定义的属性“rkeys” function collect_data(id) { db.infom_col.find({"_id":id}, function(err,doc) { if(err) throw e
function collect_data(id)
{
db.infom_col.find({"_id":id}, function(err,doc) {
if(err) throw err;
else
{
console.log("else: " + doc._id);
console.log("length: " + doc.rkeys.length);
if(typeof(doc[0].rkeys) != 'undefined' && doc[0].rkeys != null) {
for(key in doc[0].rkeys){
doc[0].rkeys[key].forEach(function(entry) {
//console.log("entry: " + entry);
ids.push(entry);
//console.log(ids);
});
}
if(ids.length > 0) {
var id1 = ids.pop();
console.log(id1);
db.infom_col.remove({"_id":id1}, function(err,doc1) {
if(err) throw err;
else {
console.log("deleted: " + id1);
var id2 = ids.shift();
console.log("going to delete: " + id2);
collect_data(id2,null);
}
});
}
}
}
});
}
更新1:
function collect_data(id,cb)
{
db.infom_col.findOne({"_id":id}, function(err,doc) {
if(err) throw err;
else
{
console.log("else: " + doc._id);
if (doc.rkeys) {
console.log("length: " + doc.rkeys.length);
for(key in doc.rkeys){
doc.rkeys[key].forEach(function(entry) {
console.log("entry: " + entry);
ids.push(entry);
});
}
if(ids.length > 0) {
var id1 = ids.shift();
console.log("id1: " + id1);
db.infom_col.remove({"_id":id1}, function(err,doc1) {
if(err) throw err;
else collect_data(id1,null);
});
}
}
}
});
}
您遇到的错误:
TypeError:无法读取未定义的属性“rkeys”
表示doc[0]
未定义
首先,我将查找更改为:
然后我会去掉doc[0]
,因为它很混乱
之后,确定是否设置了doc.rkeys:
if (doc.rkeys.length > 0)
或:
我尝试了以下方法:else{//console.log(“check-rkeys:+id”);if(doc.rkeys.length>0){for(输入doc[0].rkeys){并将find更改为findOne。但没有任何结果。不会退出,也不会删除任何内容。确保在整个代码中用doc一致地替换doc[0]。您仍在使用doc[0].rkeys在循环中也可以尝试console.log(doc),看看它是否返回任何内容。如果您可以粘贴更多信息,我可以更好地帮助您。我尝试了以下方法:console.log(“else:+doc”);if(doc.rkeys.length>0){console.log(“length:+doc.rkeys.length”);将第一个控制台作为else:[object object]然后挂断。我认为它不会进入if部分。去掉if部分,我认为它可以在没有它的情况下工作。
if (doc.rkeys.length > 0)
if (!_.isEmpty(doc.rkeys))