'Question about the syntax of a function in Node.js
I am following a tutorial to make a blog, and for the MongoDB connection in the server.js file, the instructor made a boiler connection function withDB. Operations and res are props of withDB function. In line 6, is operations a function passed a prop of the withDB functions?
Below is the withDB function.
const withDB = async (operations, res) => {
try {
const client = await MongoClient.connect('mongodb://localhost:27017', { useNewUrlParser: true });
const db = client.db('my-blog');
await operations(db); // is operations a function that takes db as its props?
client.close();
} catch (error) {
res.status(500).json({ message: 'Error connecting to db', error });
}
}
Using withDB in a function
app.get('/api/articles/:name', async (req, res) => {
withDB(async (db) => {
const articleName = req.params.name;
const articleInfo = await db.collection('articles').findOne({ name: articleName })
res.status(200).json(articleInfo);
}, res);
})
Solution 1:[1]
You're calling get() after remove(), so it's returning the next last book. If you want the removed book, just use the return value of remove():
public String pop() {
return "Book removed: " + stack.remove(stack.size()-1).getBookName();
}
Solution 2:[2]
The reason this doesn't work is that you're removing the object from the stack, then trying to find it still in the stack. That is, you're calling remove correctly, but then you're calling get on the same stack, which is going to return the next available element if there is one.
Fortunately, the remove method actually returns the object that it removed. So you could write something like
public String pop()
{
Book removedBook = stack.remove(stack.size()-1);
return "Book removed: " + removedBook.getBookName();
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | shmosel |
| Solution 2 | Dawood ibn Kareem |
