0
const {category, parent} = newCategory;
        const newCat = new Category({
            _id: new mongoose.Types.ObjectId(),
            name: category,
            parent: parent
        }).save((err, res) => {
            if(err) { console.log(err)}
            else{
                console.log("res in create category:", res);
                // io.to(user.room).emit('create-category-to-list', {res});
            }
        })

在日志中

   res in create category: {    
    codewords: [],  
    children: [],  
    _id: 604916cf866a154e284b2e29, 
    name: 'nameofasdasdasdcat',   
    parent: 60490c9ce00e8b7a38cf4752,
    path: '60490c9ce00e8b7a38cf4752#604916cf866a154e284b2e29',  
    _v:0
}

此处创建了文档,但未将其分配给其父级为什么会发生这种情况。

在这里你可以看到父子数组是空的

root: {     
    children: [],  
    _id: 60490c9ce00e8b7a38cf4752,    
    name: 'root',         
    path: '60490c9ce00e8b7a38cf4752',   
    _v:0
}

在这里,我使用 mongoose pulgin(mongoose-mpath) 创建树形数据。

对于猫鼬-mpath https://www.npmjs.com/package/mongoose-mpath

4

1 回答 1

0

在 getChildrenTree 函数中需要将选项传递为lean:false

const parent = await Folder.findOne({ _id: user.rootId });
const tree = await parent.getChildrenTree(
   { 
     populate: 'codewords', 
     options: { lean: false } //you need to pass options as lean: false
   });
console.log({ tree });

在日志中

{
  tree: [
    {
      codewords: [],
      children: [],
      _id: 604c6c5bc8a2e03ee43c4c7b,
      name: 'Category-name-2',
      parent: 604c690b87924705a401f9ce,
      path: '604c690b87924705a401f9ce#604c6c5bc8a2e03ee43c4c7b',
      __v: 0
    },
    {
      codewords: [],
      children: [],
      _id: 604c6ce2c8a2e03ee43c4c7d,
      name: 'Category-name-2',
      parent: 604c690b87924705a401f9ce,
      path: '604c690b87924705a401f9ce#604c6ce2c8a2e03ee43c4c7d',
      __v: 0
    },
    {
      codewords: [],
      children: [Array],
      _id: 604c6d21c8a2e03ee43c4c7e,
      name: 'Category-name-3',
      parent: 604c690b87924705a401f9ce,
      path: '604c690b87924705a401f9ce#604c6d21c8a2e03ee43c4c7e',
      __v: 0
    }
  ]
}

为了您更好地理解,您可以查看 mongoose-mpath github 问题部分 ==> https://github.com/vikpe/mongoose-mpath/issues/10

于 2021-03-13T08:29:58.697 回答