簡體   English   中英

ZCCADCDEDB567ABAE643E15DCF0974E503Z 未填充 MongoDB 中的字段

[英]Mongoose is not populating the fields in MongoDB

當我運行以下代碼時,我得到了 object 以及控制台上記錄的填充字段。 截屏

但是,這些字段尚未填充到圖書收藏中。 有人可以幫我解決這個問題嗎?

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);
});

這就是人口的工作方式,它只存儲對數據庫中其他文檔的引用。 在查詢時,如果您要求它(使用.populate() ),ZCCADCDEDB567ABAE643E15DCF0974E503Z 將檢索引用的文檔並將它們插入到“父”文檔中。

如果要將引用的文檔存儲在數據庫中,則不能使用 population 但必須使用subdocuments

但是,這會限制數據庫的靈活性,因為如果需要更改作者姓名,則需要更改數據庫中的所有 Book 文檔以更新作者姓名。 使用人口,您只需要更改作者文檔。

建立連接成功了嗎

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM