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

时间:2014-07-13 09:32:06

标签: node.js mongodb mongoose

//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

//我可以从书签中删除一个项目,不会出现问题

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

问题!! 如何删除标签数组中的标签,在书签数组中给定用户_id,书签_id和标签_id或名称?

//我尝试过以下各种变体而没有成功

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)

最初我使用的是不同的模型和子文档。

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]
} );

但是,我无法使用上面使用的$ pull命令从子文档中删除项目。所以我恢复使用一个架构/模型。 这是一项非常重要的任务,能够完成,我会很乐意提供帮助。

感谢穆罕默德但我无法使用这两种方法中的任何一种: 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)我不得不使用lean()函数将Mongoose Document数据格式转换为普通JSON。否则bookmarks.push({link:user.bookmarks[i].link,_id:user.bookmarks[i]._id,tags:tags})

无法正确组合:

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

关于书签[]

然而,使用lean()函数意味着我无法使用.save将数据保存到数据库

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

1 个答案:

答案 0 :(得分:0)

从JSON doc的子文档中删除

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

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]);
        }
 }

})