What is the output of the following Node.js code using the MongoDB driver?
4 phương ánCó giải thích
const { MongoClient } = require('mongodb');
async function run() {
const client = new MongoClient('mongodb://localhost:27017');
try {
await client.connect();
const db = client.db('test');
const collection = db.collection('products');
await collection.insertOne({ name: 'Laptop', price: 1000 });
const result = await collection.findOne({ price: { $gte: 500 } });
console.log(result.name);
} finally {
await client.close();
}
}
run();Assume the `products` collection is initially empty.
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: "Laptop". Lần theo mã: client.connect() mở kết nối tới máy chủ cục bộ, client.db('test').collection('products') lấy collection products đang rỗng; insertOne chèn tài liệu có name là Laptop và price là 1000; findOne với điều kiện price $gte 500 tìm tài liệu đầu tiên có giá lớn hơn hoặc bằng 500, chính là tài liệu vừa chèn vì 1000 thoả điều kiện; console.log(result.name) in Laptop, rồi khối finally đóng kết nối. "undefined" chỉ xảy ra khi tài liệu tìm được không có trường name. "Throws an error due to connection failure" sai vì mã chạy với máy chủ MongoDB ở localhost hoạt động bình thường, không có dấu hiệu lỗi kết nối. "null" là giá trị findOne trả về khi không có tài liệu khớp, nhưng ở đây có tài liệu khớp, và lệnh in result.name chứ không in result.
Cùng chương 4
What is MongoDB?Có lời giảiCâu hỏiWhat is the purpose of using regex in MongoDB queries?Có lời giảiCâu hỏiTo connecting to a MongoDB database and performing CRUD operations using the Node MongoDB Driver. Identify the parts responsible for connecting, inserting, and querying documents. (Choose 3 answers)Có lời giảiCâu hỏiCả 36 câu của chủ đề36 câu