What is the MOST likely issue in the following code? const posts = await Post.find().populate("writer"); Schema: author: { type: Schema.Types.ObjectId, ref: "User" }
4 phương ánCó giải thích
Các phương án trả lời
Chọn một phương ánLời giảiChọn phương án để mở
Đáp án đúng: "Wrong path name used in populate". Đối số của populate() là tên đường dẫn (path) có trong schema chứ không phải tên tuỳ ý; schema chỉ có trường author với ref tới User, còn mã lại gọi populate với writer. Từ Mongoose 6, tuỳ chọn strictPopulate mặc định bật nên lệnh này ném lỗi báo không thể populate path writer vì nó không có trong schema; ở bản cũ hơn nó lặng lẽ không làm gì và author vẫn là ObjectId. Cách sửa là populate với author. ".populate() only works with arrays" sai vì populate dùng được cho cả trường ObjectId đơn lẫn mảng ObjectId. "find() must come after populate" sai vì populate là method nối vào query do find() trả về, nên thứ tự Post.find().populate(...) là đúng. "ObjectId cannot reference User model" sai vì khai báo type ObjectId kèm ref tới User chính là cách tham chiếu chuẩn.
Cùng chương 5
Which of the following are true about the match option in the populate() method? (Choose 2 answers)Có lời giảiCâu hỏiWhich of the following are valid options for the populate() method in Mongoose? (Choose 2 answers)Có lời giảiCâu hỏiWhat are not use cases for Mongoose in Node.js?Có lời giảiCâu hỏiCả 45 câu của chủ đề45 câu