简体   繁体   中英

How to query a mongo document using mongoose?

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

Use$pull

Example:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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