Câu hỏi: SDN302 Server-Side development with NodeJS, Express, and MongoDB – Bộ ôn tập cuối kỳ số 2
50 câu trắc nghiệm kèm lời giải của môn Server-Side development with NodeJS, Express, and MongoDB, xếp đúng thứ tự trong đề. Trang 3/3 — câu 41–50.
Danh sách câu hỏi
const mongoose = require('mongoose');mongoose.connect('mongodb://localhost:27017/db');
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();Đáp án đúng: "Kid". Lần theo mã:
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.
const fs = require('fs');
fs.readFile('file.txt', 'utf8', (err, data) => {
if (err) console.log('Error occurred');
else console.log(data);
});
console.log('Reading file');Reading file
Error occurredError occurred
Reading fileconst fs = require('fs');
const util = require('util');
const readFile = util.promisify(fs.readFile);
async function main() {
try {
const data = await readFile('config.json', 'utf8');
console.log('Success:', data);
} catch (err) {
console.log('Error:', err.message);
}
console.log('Done');
}
main();Assume 'config.json' does NOT exist.
Success: undefined
DoneError: ENOENT: no such file or directory, open 'config.json'
DoneDone
Error: ENOENT: no such file or directory, open 'config.json'const express = require('express');
const router = express.Router();
router.get('/', (req, res) => {
res.send('respond with a resource');
});
module.exports = router;