【问题标题】:How to delete hierarchical structure using mongoose ,Node.js?如何使用猫鼬,Node.js 删除层次结构?
【发布时间】:2018-01-16 16:48:35
【问题描述】:

我的架构层次结构是...... List -> Items -> (attachements,comments,labels)

Que:所以如果我想删除一个列表,所有引用的(分层)元素都应该删除。这里(attachments,cmets,labels)引用了Item 和 Item 引用到 List。所以请给我一些建议。 架构:

List:{
 list_title: {type: String, required: true},
    created_at: Date,
    updated_at: Date
}
Item:{
 item_title: {type: String, required: true},
  discription:{type: String},
  label : {type:Array ,label_id : String },
  created_at: Date,
  updated_at: Date,
  _list: {type: Schema.Types.ObjectId, ref:'List'}
}
Comment:{
  comment:{type:String},
  created_at: Date,
  updated_at: Date,
  entity_id : {type: Schema.Types.ObjectId, ref:''},
  model : {type : String ,enum : ['Item','File'] }
}
Attachment:{
   title : [{type : String}],
     // files: [String],
       path : [String],
      make_cover : {type : Boolean },
    _item: {type: Schema.Types.ObjectId, ref:'Item'}
    }

提前致谢

【问题讨论】:

    标签: node.js express mongoose


    【解决方案1】:

    当您使用 Mongoose 进行搜索时,您会收到 Mongoose 对象。每个 Mongoose 对象都有存储在它所代表的文档中的所有信息(列表 -> 项目 ->(附件、cmets、标签) 当您在 Node.js 中拥有要使用的对象时,您可以在对象中删除您不再需要的所有元素,最后,您可以调用 .save() 方法以及您在其中所做的所有更改该对象将保存在 MongoDB 中

    例子:

    myCollection.findOne({name: "myName"},  function(err, obj) {
        // obj is the Mongoose object with all the information in the document in DB
        // Here you can remove elements from obj, imagine you want to remove first item in the first element of List
        obj.List[0].splice(0, 1);
        // Finally, we save changes in DB
        obj.save();
    })
    

    【讨论】:

    • 通过这样做,只会删除与该列表关联的那些信息。但我还想删除附件、cmets、标签。
    • 这只是一个例子。我的意思是,您可以删除该对象(包括附件、cmets 等)中所需的任何内容,并且当您调用该对象的 .save() 方法时,所有这些元素都将在数据库中删除。试试看,让我知道它是否适合你
    • 我收到一个错误:TypeError: Cannot read property 'splice' of undefined
    • 我告诉过你,这是一个例子。根据您的架构,List 不是列表:S,因此请修改真正存在的元素 :)
    猜你喜欢
    • 2021-09-22
    • 2021-07-28
    • 1970-01-01
    • 2021-12-21
    • 1970-01-01
    • 1970-01-01
    • 2021-11-21
    • 2021-07-08
    • 2014-08-03
    相关资源
    最近更新 更多