What is the result of populating in this Mongoose code?

4 phương ánCó giải thích
Đề bài
const mongoose = require('mongoose');

mongoose.connect('mongodb://localhost:27017/db');

Đề bài
const childSchema = new mongoose.Schema({ name: String });
const parentSchema = new mongoose.Schema({ child: { type: mongoose.Schema.Types.ObjectId, ref: 'Child' } });
const Child = mongoose.model('Child', childSchema);
const Parent = mongoose.model('Parent', parentSchema);
async function run() {
    const child = await Child.create({ name: 'Kid' });
    await Parent.create({ child: child._id });
    const parent = await Parent.findOne().populate('child');
    console.log(parent.child.name);
}
run();

Các phương án trả lời

Chọn một phương án
Lời giảiChọn phương án để mở

Đáp án đúng: "Kid". Lần theo mã:

Lời giải
Child.create({
  name: 'Kid'
}

) tạo tài liệu con và trả về nó kèm _id; Parent.create lưu một tài liệu cha có trường child chỉ chứa ObjectId đó, vì parentSchema khai báo child là ObjectId với ref: 'Child'; Parent.findOne().populate('child') dùng ref để truy vấn thêm collection của model Child và thay ObjectId bằng cả tài liệu con, nên parent.child là object có name bằng Kid, và console.log(parent.child.name) in ra Kid. "The child's name if reference resolved" chỉ mô tả có điều kiện, không phải chuỗi in ra cụ thể. "Full parent document with embedded child" sai vì lệnh log chỉ in thuộc tính name, không in cả tài liệu cha. "Populated field value from linked model" là mô tả chung về cơ chế populate, không nêu kết quả cụ thể mà câu hỏi cần.

Cùng chương 5

Xuất hiện trong 1 bộ đề