Home > Back-end >  Mongoose is not populating the fields in MongoDB
Mongoose is not populating the fields in MongoDB

Time:09-20

When I run the following code, I get the object along with the populated fields logged on the console. Screenshot

But, the fields have not been populated in the books collection. Can someone please help me figure this out?

const bookSchema = new Schema({
  title: String,
  genre: { type: Schema.Types.ObjectId, ref: "genre" },
  author: { type: Schema.Types.ObjectId, ref: "author" },
  numberInStock: { type: Number, default: 0 },
  rating: Number,
  yearPublished: Number,
  dateAdded: { type: Date, default: Date.now },
  liked: { type: Boolean, default: false },
});
const genreSchema = new Schema({ name: String });
const authorSchema = new Schema({ name: String });

const Book = model("book", bookSchema);
const Genre = model("genre", genreSchema);
const Author = model("author", authorSchema);

const books = [
  {
    title: "Sapiens",
    genre: "632873144b0bbfc10ae1942d",
    author: "632873e706fe265eaee77de3",
    numberInStock: 6,
    rating: 4.4,
    yearPublished: 2011,
  },
];

async function saveBook(b) {
  let book = new Book(b);
  book
    .save()
    .then((result) => {
      populateBook(result._id);
    })
    .catch((err) => console.log("Error: ", err));
}

function populateBook(id) {
  Book.findById(id)
    .populate("genre")
    .populate("author")
    .exec((err, book) => {
      if (err) {
        console.log("Error: ", err);
        return;
      }
      console.log(book);
    });
}

books.forEach((b) => {
  saveBook(b);
});

CodePudding user response:

That's how population works, it only stores references to other documents in the database. At query time, and if you ask for it (using .populate()), Mongoose will retrieve the referenced documents and insert them into the "parent" document.

If you want the referenced documents to be stored in the database, you can't use population but have to use subdocuments.

However, this will limit the flexibility of your database, because if for example an author name needs to be changed, you need to change all the Book documents in your database to update the author's name. With population, you only need to change the Author document.

CodePudding user response:

Did you establish the connection successfully

  • Related