Home > Software design >  How to query a mongo document using mongoose?
How to query a mongo document using mongoose?

Time:09-30

MongoDB documents contain an array of objects and what is the best way to query those documents if I want to find and remove an object from an array with some specific value;

Here is an example of the document schema

const mongoose = require("mongoose");

const LibrarySchema = new mongoose.Schema({
  user: {
    type: mongoose.Schema.Types.ObjectId,
    required: true,
  },
  books: [
    {
      type: new mongoose.Schema({
        bookName: {
          type: String,
          required: true,
        },
        chapterReading: {
          type: Number,
          default: 1,
          required: true,
        },
      }),
    },
  ],
});

const Library = mongoose.model("Library", LibrarySchema);

exports.Library = Library;

If I want to find and remove a book with some bookName

CodePudding user response:

Use $pull

Example :

Library.update({}, { $pull: { books: { bookName: "Yourbookname" } } })
  • Related