0

I have a user schema and each user have a profile in which he has a collection of book, and the user wants to remove a single book from the bookCollection, I have tried my code is at the bottom. The user schema is as follows:

var bookSchema = new Schema({
title: {
    type: String,
    required: true,
},
author: {
    type: String,
    required: true,
},
publisher: {
    type: String,
    default: "not set"
},
desc: {
    type: String,
    default: "not set"
},
availableAs: {
    type: String, //either hardcopy or softcopy
    required: true
},

price: {
    type: Number,
    default: 0
},
category: {
    type: String,
    default: "not set"
},
imageurl: {
    type: String,
    default: 'nobook.png'

},
bookurl: {
    type: String,
    default: ''
},
softcopy_available: {
    type: Number,
    default: 0
}
});





var userSchema = new Schema({
 admin: {
    type: Boolean,
    default: false
 },
 bookCollection: [bookSchema]
});

This is what I am trying, but deletion is not working, sometimes it shows error and the page keeps on loading.

router.post('/', (req, res, next) => {
console.log(req.body.bookid);
var id=req.body.bookid;

users.findOne({

    })
    .then((user1) => 
        user1.bookCollection.pull(req.body.bookid._id);
    })
    .catch((err) => {
        next(err)

    });
});
prax
  • 286
  • 3
  • 10

1 Answers1

0

Why don't you use updateOne, or UpdateMany to pull the book from bookcollection, if you need to remove from a single user

var ObjectId = mongoose.Types.ObjectId;

users.updateOne({_id: ObjectId(user_id)},{ $pull: { bookCollection: { _id: ObjectId(req.body.bookid._id) } }})
.then((results) => 
    // results of your update query
})
.catch((err) => {
    next(err)

});

If want to remove a certain book from all the users

var ObjectId = mongoose.Types.ObjectId;

users.updateMany({},{ $pull: { bookCollection: { _id: ObjectId(req.body.bookid._id) } }})
.then((results) => 
    // results of your update query
})
.catch((err) => {
    next(err)
});
Puneet Singh
  • 3,477
  • 1
  • 26
  • 39
  • hey ! thanks for your help! I have one more query i have found on solution on Mongoose documentation and i found this code `user1.bookCollection.pull({ _id:id});` .It works for me but when I try to pull again after removing once it doesn't show any error.How can a object with a single id can be deleted twice . What is the mistake? ;) – prax May 20 '20 at 14:53
  • Can you share the document link – Puneet Singh May 20 '20 at 16:33
  • Here is the link :https://mongoosejs.com/docs/api/array.html#mongoosearray_MongooseArray-pull – prax May 21 '20 at 06:54