Danh sách câu hỏi của đề

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

50/50 câuHết danh sá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();
AKid
BThe child's name if reference resolved
CFull parent document with embedded child
DPopulated field value from linked model
Lời giải

Đá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.

Mở trang câu hỏi này →
Afs
Bhttp
Cexpress
Dpath
Lời giải
Đáp án đúng: "express". Đây là câu phủ định: cần chọn thứ không phải core module (module lõi, có sẵn khi cài Node.js). Express là framework web của bên thứ ba, phân phối qua npm, phải chạy npm install express rồi mới require được và nó nằm trong thư mục node_modules của dự án. "fs" là core module dùng đọc, ghi, xoá tệp và thư mục, như fs.readFile hay fs.writeFile, nên đúng là module lõi và không được chọn. "http" là core module dùng tạo máy chủ và gửi request HTTP bằng http.createServer hay http.request; chính Express cũng dựng trên module này. "path" là core module xử lý đường dẫn tệp, ví dụ path.join và path.resolve, giúp ghép đường dẫn đúng trên mọi hệ điều hành. Cả ba đều require được ngay mà không cần cài thêm gói nào.
Mở trang câu hỏi này →
AA new programming language developed by Mozilla
BA JavaScript runtime environment for server-side development
CA framework like React or Angular
DA NoSQL database system
Lời giải
Đáp án đúng: "A JavaScript runtime environment for server-side development". Node.js là môi trường chạy (runtime) JavaScript dựng trên engine V8 của Chrome, bổ sung vòng lặp sự kiện (event loop) và I/O bất đồng bộ qua libuv cùng các module như fs, http, nhờ đó JavaScript chạy được ngoài trình duyệt để viết máy chủ web và công cụ dòng lệnh. "A new programming language developed by Mozilla" sai hai chỗ: Node.js không phải ngôn ngữ mới mà chạy chính JavaScript, và nó không do Mozilla phát triển. "A framework like React or Angular" sai vì React và Angular là thư viện, framework giao diện chạy ở trình duyệt, còn Node.js là nền chạy mà các framework như Express dựng lên trên. "A NoSQL database system" sai vì Node.js không lưu dữ liệu; nó kết nối tới cơ sở dữ liệu NoSQL như MongoDB thông qua driver.
Mở trang câu hỏi này →
Đề bài
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');
AReading file Error occurred
BError occurred Reading file
CLogs reading then handles file absence gracefully
DOnly reading log if file check skipped
Lời giải
Đáp án đúng: "Reading file Error occurred". Hàm fs.readFile là bất đồng bộ: nó giao việc đọc tệp cho libuv rồi trả về ngay, callback chỉ được gọi ở một lượt event loop sau khi thao tác I/O xong. Lần theo mã: lệnh gọi readFile đăng ký callback, tiếp theo console.log('Reading file') chạy đồng bộ nên dòng Reading file được in trước; sau đó việc mở file.txt thất bại với lỗi ENOENT, callback nhận err khác null nên vào nhánh if và in Error occurred. "Error occurred Reading file" sai thứ tự vì callback không thể chạy trước phần mã đồng bộ còn lại của chương trình. "Logs reading then handles file absence gracefully" mô tả bằng lời đúng tinh thần nhưng không cho biết chính xác những gì được in, trong khi câu hỏi cần kết quả cụ thể trên console, nên phương án ghi rõ hai dòng theo đúng thứ tự mới là lựa chọn chính xác. "Only reading log if file check skipped" sai vì mã không có bước kiểm tra tệp nào bị bỏ qua, cả hai lệnh log đều chạy.
Mở trang câu hỏi này →
45What is the output of the following Node.js code?4 lựa chọncó code
Đề bài
const 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.

ASuccess: undefined Done
BError: ENOENT: no such file or directory, open 'config.json' Done
CDone Error: ENOENT: no such file or directory, open 'config.json'
DThrows an unhandled promise rejection
Lời giải
Đáp án đúng: "Error: ENOENT: no such file or directory, open 'config.json' Done". Lần theo mã: util.promisify biến fs.readFile kiểu callback thành hàm trả về Promise; trong main, await readFile('config.json', 'utf8') chờ Promise đó, và vì tệp không tồn tại nên Promise bị reject với lỗi mã ENOENT, message là ENOENT: no such file or directory, open 'config.json'; await ném lỗi vào khối catch, in dòng Error kèm message, rồi chạy tiếp ra ngoài try/catch in Done, nên hai dòng xuất hiện theo thứ tự lỗi trước, Done sau. "Success: undefined Done" sai vì dòng Success chỉ chạy khi đọc tệp thành công, ở đây readFile thất bại nên lệnh đó bị bỏ qua. "Done Error: ENOENT: no such file or directory" sai thứ tự: await làm main dừng chờ, còn console.log('Done') đứng sau toàn bộ try/catch nên không thể in trước lỗi. "Throws an unhandled promise rejection" sai vì lỗi đã được bắt bởi catch bên trong hàm async, Promise của main hoàn tất bình thường.
Mở trang câu hỏi này →
AStoring in MongoDB for consistency
BUsing GridFS for large files in DB
CDisk storage with Multer
DIn-memory storage
Lời giải
Đáp án đúng: "Disk storage with Multer". Với multer.diskStorage, tệp được ghi thẳng xuống hệ thống tệp theo dạng luồng, cơ sở dữ liệu chỉ lưu metadata nhẹ như tên tệp, đường dẫn, kích thước; nhờ vậy MongoDB không phải gánh khối dữ liệu nhị phân lớn, sao lưu và truy vấn nhẹ hơn, còn phần lưu trữ tệp có thể mở rộng riêng (thêm ổ đĩa, chuyển sang dịch vụ lưu trữ đối tượng). "Storing in MongoDB for consistency" bị giới hạn bởi kích thước tối đa 16 MB của một document BSON và làm phình cơ sở dữ liệu, nên không phù hợp với tệp lớn. "Using GridFS for large files in DB" là cách MongoDB chia tệp vượt 16 MB thành nhiều chunk và vẫn dùng được, nhưng toàn bộ dữ liệu tệp vẫn nằm trong cơ sở dữ liệu nên tải đọc ghi và dung lượng dồn lên MongoDB, kém linh hoạt hơn khi tệp nhiều và lớn. "In-memory storage" (multer.memoryStorage) giữ cả tệp trong RAM dưới dạng Buffer, tệp lớn hoặc nhiều request đồng thời dễ làm cạn bộ nhớ tiến trình.
Mở trang câu hỏi này →
Adestination: function (req, file, cb) { cb(null, 'files/'); }
Bdestination: function (req, file, cb) { cb(null, 'uploads/'); }
Cfilename: function (req, file, cb) { cb(null, 'uploads/'); }
Dstorage: function (req, file, cb) { cb(null, 'uploads/'); }
Lời giải
Đáp án đúng: "destination: function (req, file, cb) { cb(null, 'uploads/'); }". Khi cấu hình multer.diskStorage với hai khoá destination và filename, hàm destination nhận req, file và callback cb; gọi cb(null, 'uploads/') nghĩa là không có lỗi (đối số đầu là null) và lưu tệp vào thư mục uploads. Lưu ý khi destination là hàm, Multer không tự tạo thư mục, nên uploads phải có sẵn. Đoạn trả về "cb(null, 'files/')" đặt đúng khoá destination nhưng ghi vào thư mục files, không phải uploads như yêu cầu. "filename: function (req, file, cb) { cb(null, 'uploads/'); }" đặt sai khoá: filename quyết định tên tệp được lưu, truyền 'uploads/' vào đó sẽ thành tên tệp chứ không chọn được thư mục. "storage: function (req, file, cb) { cb(null, 'uploads/'); }" sai vì storage là tuỳ chọn của multer() nhận một engine lưu trữ do multer.diskStorage() tạo ra, không phải một hàm callback chỉ thư mục.
Mở trang câu hỏi này →
AIt sets up a project skeleton with the necessary files and folders.
BIt compiles JavaScript code into machine code.
CIt allows you to focus on building your application's features instead of setting up the initial boilerplate code.
DIt is used to manage user authentication and sessions.
Lời giải
Đáp án đúng gồm hai ý: "It sets up a project skeleton with the necessary files and folders." và "It allows you to focus on building your application's features instead of setting up the initial boilerplate code.". Express Generator là gói express-generator, chạy bằng npx express-generator, sinh sẵn khung dự án gồm app.js, bin/www, các thư mục routes, views, public và package.json với những middleware cơ bản, nhờ vậy lập trình viên khỏi viết tay phần mã khởi tạo lặp lại (boilerplate) và vào thẳng phần tính năng. "It compiles JavaScript code into machine code." sai vì việc biên dịch JIT là của engine V8 trong Node.js, Express Generator chỉ tạo tệp và thư mục. "It is used to manage user authentication and sessions." sai vì xác thực và phiên do các thư viện như Passport hay express-session đảm nhận; khung được sinh ra không kèm sẵn chức năng đăng nhập.
Mở trang câu hỏi này →
Đề bài
const express = require('express');
const router = express.Router();
router.get('/', (req, res) => {
  res.send('respond with a resource');
});
module.exports = router;
Arespond with a resource
B404 status with 'Cannot GET /users'
C{ message: 'Users route' }
DThrows an error due to missing route
Lời giải
Đáp án đúng: "respond with a resource". Lần theo mã: app.js do express-generator sinh ra có dòng app.use('/users', usersRouter), gắn router của users.js vào tiền tố /users; trong router, router.get('/') khớp phần đường dẫn còn lại sau tiền tố, nên GET http://localhost:3000/users rơi đúng vào handler này và res.send gửi chuỗi respond with a resource với mã 200, kiểu text/html. "404 status with 'Cannot GET /users'" chỉ xảy ra khi không có route nào khớp, trong khi mẫu mặc định đã gắn sẵn usersRouter. "{ message: 'Users route' }" sai vì handler gửi chuỗi chứ không gửi object JSON, và nội dung đó không có trong mã. "Throws an error due to missing route" sai vì route tồn tại và chạy bình thường, server khởi động ở cổng 3000 theo tệp bin/www.
Mở trang câu hỏi này →
50Which module is used for setting up your Express server to accept file uploads?4 lựa chọnTrung bình50% trả lời đúng
Apath
Bhttp
Cmulter
Dbody-parser
Lời giải
Đáp án đúng: "multer". Multer là middleware cho Express chuyên xử lý dữ liệu multipart/form-data, kiểu mã hoá mà form HTML dùng khi gửi tệp. Sau khi cấu hình nơi lưu (diskStorage hoặc memoryStorage) và gắn vào route, ví dụ upload.single('avatar'), multer đọc phần tệp của request, lưu lại và gắn thông tin tệp vào req.file hoặc req.files, các trường chữ đi kèm vào req.body. "path" là core module xử lý đường dẫn tệp, có thể hỗ trợ đặt tên hay đường dẫn lưu nhưng không tự nhận tệp tải lên. "http" là core module tạo máy chủ ở mức thấp; tự phân tích multipart bằng nó rất phức tạp và không phải cách thiết lập thông thường. "body-parser" chỉ phân tích phần thân dạng JSON, urlencoded, raw hoặc text, và tài liệu của nó nói rõ không xử lý multipart, nên không nhận được tệp.
Mở trang câu hỏi này →