Thursday, 14 November 2019

Mongoose Query: Remove object from array

I have a list of authors and quotes. Quotes are not their own schema, but they have their own id values since they're embedded objects. I want to find that author and remove that quote.Here's my model and my current query. However, I'm getting the error that I cannot use Id to traverse the objects. I'm not sure what else would be reasonable to use. The content is quite long at times, and multiple quotes can have the same rank.const AuthorSchema = new mongoose.Schema({ name: {type: String, required: [true, "Author Name is Required"], minlength: [3,"Name must be at least 3 characters"]}, quotes: [{content: {type: String, required:[true, "Quote is Required"], minlength: [3,"Quote must be at least 3 characters"]}, rank: {type: Number}}] }, {timestamps: true}) //remove quote from Author app.put("/authors/:id/:Qid/remove", (req, res) => { //delete quote Author.findOneAndUpdate({_id: req.params.id},{$pull: {"quotes._id": req.params.Qid}}) .then(data => res.json({message: "success", result: data})) .catch(err => res.json({badresult:err})); });

Submitted November 14, 2019 at 10:50PM by newb2coding

No comments:

Post a Comment