我正在使用下面的函数来构建树列表,并且对本地obj_list
对象很满意,为什么那对mongodb doc
对象不起作用?
代码:
const promise = Tree.find({uid: mongoose.Types.ObjectId('5c17974259bf01254c9c7f56')}, {'_id': false, 'uid': false}).exec();
promise.then(async (doc) => {
const obj_list = doc; // not work with doc object in db
const obj_list = [{ // work localy
nid: 1,
name: 'father',
parent: '0',
__v: 0,
},
{
nid: 2,
name: 'boy',
parent: '1',
__v: 0,
}];
console.log(doc);
console.log(obj_list);
const obj_nested_list = [];
let obj;
function fill_with_children(children_arr, parent_id) {
for (let i = 0; i < obj_list.length; i++) {
obj = obj_list[i];
if (obj.parent == parent_id) {
children_arr.push(obj);
obj.children = [];
fill_with_children(obj.children, obj.nid);
}
}
}
fill_with_children(obj_nested_list, 0);
console.log(obj_nested_list);
}).catch((err) => {
if (err) {
console.log(err);
}
});
console.log(doc):
[ { nid: 1, name: 'father', parent: '0', __v: 0 },
{ nid: 2, name: 'boy', parent: '1', __v: 0 } ]
console.log(obj_list):
[ { nid: 1, name: 'father', parent: '0', __v: 0 },
{ nid: 2, name: 'boy', parent: '1', __v: 0 } ]
带有doc的输出: //不好
[ { nid: 1, name: 'father', parent: '0', __v: 0 } ]
使用obj_list输出: //确定
[ { nid: 1,
name: 'father',
parent: '0',
__v: 0,
children: [ [Object] ] } ]
答案 0 :(得分:1)
猫鼬查询承诺解析为Document
对象,而不是纯JavaScript对象。如果您希望普通的JavaScript对象进行操作和记录,则应使用Query#lean
:
const promise = Tree.find(…).lean().exec();
promise.then(…);