简体   繁体   English

NodeJs MongoDb Mongoose-如何从多维数组中删除项目?

[英]NodeJs MongoDb Mongoose - How to Delete item from Multi Dimensional Array?

//MONGOOSE SCHEMA OBJECT
var userSchema = new Schema( {
  username: { type: String, required: true, unique: true },
  email: { type: String, required: true, unique: true },
  tags:[ {name : String, color : String } ],
  bookmarks:[{link : String, tags:[ {name : String, color : String } ]}]
} );

module.exports = userSchema;        //Export the userSchema
var UserModel = mongoose.model('UserModel', userSchema ); //Create Model
module.exports = UserModel;      //Export the Model

//I CAN DELETE AN ITEM FROM BOOKMARKS ARRAY NO PROBLEM USING //我可以使用书签从书签中删除项目

UserModel.findByIdAndUpdate(userId ,{$push : {bookmarks: {link : req.body.link, tags : req.body.tags}}}, function(err, user_data) {

PROBLEM!! 问题!! How do I delete a tag from the tags Array, within the bookmarks array given users _id, bookmarks _id and the tag _id or name? 在给定用户_id,书签_id和标签_id或名称的书签数组中,如何从标签数组中删除标签?

//I have tried variations of the following without success //我尝试了以下变化,但未成功

var update = {bookmarks:[{ _id : bookmarkId},
$pull: {tags:[_id : tagid ] }] };

UserModel.findByIdAndUpdate(userId ,update, function(err, user_data) {

AND

UserModel.findOne( {_id : userId}).select({ bookmarks:[ { $elemMatch: {_id : req.params.bookmarkId}}] }).exec(function(err, user_data)

Initially I was using different Models and subdocuments. 最初,我使用的是不同的模型和子文档。

var bookmarkSchema = new Schema( {
    link : String,
    tags:[tagSchema]
});

var tagSchema = new Schema( {
    name : String,
    color : String
});

var userSchema = new Schema( {
  username: { type: String, required: true, unique: true },
  email: { type: String, required: true, unique: true },
  tags:[ {name : String, color : String } ],
  bookmarks: [bookmarkSchema]
} );

However, I was unable to delete items from the subdocuments using the $pull command like I used above. 但是,我无法像上面使用的那样使用$ pull命令从子文档中删除项目。 So I reverted to just using one schema/model. 因此,我恢复为仅使用一个架构/模型。 This is a very important task to be able to complete and I would be greatful for help. 这是完成一项非常重要的任务,我将不胜感激。

Thanks Muhammad but I could not get either of the 2 methods to work: 1) Nothing happens to DB and the values of the callbacks are: *numberAffected: 0 *raw: {"updatedExisting":false,"n":0,"connectionId":322,"err":null,"ok":1} 感谢Muhammad,但我无法使用这两种方法中的任何一种:1)DB没有任何反应,回调的值是:* numberAffected:0 * raw:{“ updatedExisting”:false,“ n”:0,“ connectionId“:322,” err“:null,” ok“:1}

UserModel.update({bookmarks:req.params.bookmarkId},
    { $pull: {"bookmarks.tags" :{_id:req.body._id, name :req.body.name ,color:req.body.color}}}, function(err, numberAffected, raw) {

2) I had to use the lean() function to convert Mongoose Document data format to normal JSON. 2)我必须使用lean()函数将Mongoose Document数据格式转换为普通JSON。 Otherwise bookmarks.push({link:user.bookmarks[i].link,_id:user.bookmarks[i]._id,tags:tags}) 否则, bookmarks.push({link:user.bookmarks[i].link,_id:user.bookmarks[i]._id,tags:tags})

would not combine properly with: 不能与以下内容正确组合:

bookmarks.push(user.bookmarks[i]); bookmarks.push(user.bookmarks [i]);

on bookmarks[] 在书签上[]

However using the lean() functions means I would not be able to save the data to the DB with .save 但是,使用lean()函数意味着我将无法使用.save将数据保存到DB中。

UserModel.findById(userId).lean(true).exec(function(err, user) {

delete from sub-Document of JSON doc, 从JSON文档的子文档中删除,

UserModel.update({bookmarks:bookmarkId},{$pull: {"bookmarks.tags" :{_id:tagsId,name :name ,color:color}}}, function(err, user_data) {

or 要么

UserModel.findOnd(userId,function(er,user){
 var bookmarks= [];
 var tags = [];
 for (var i = 0;i<user.bookmarks.length;i++){
   if (user.bookmarks[i]._id==bookmarkId)
   {
    for (var j = 0;j<user.bookmarks[i].tags.length;j++){
      if (user.bookmarks[i].tags[j]._id==tagid )
      {

      }else {
         tags.push(user.bookmarks[i].tags[j])
       }
     }
    bookmarks.push({link:user.bookmarks[i].link,_id:user.bookmarks[i]._id,tags:tags})
   }
   else {
       bookmarks.push(user.bookmarks[i]);
        }
 }

})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM