This lesson will walk you through replacing the app's file system reliance with a live MongoDB database. We'll also use a popular ORM library to manage our database operations.
Really excellent course Ben. It would be great to see more on Mongoose/MongoDB with express.
Thanks, Nicholas! I actually started on a new Mongoose lesson yesterday, and have 2 or 3 planned after that. :)
Hello, i tried to repeat this code, but i've got an err. mongoose return an empty array. exports.User= mongoose.model('User', userSchema, 'user'); works fine fith 3th param.
Did you populate your database using the command shown?
mongoimport --db test --collection users --drop --file user_list.json
The default behavior of mongoose.model()
is to use the plural form of the model name for the collection. So mongoose.model('User', userSchema)
will look for a users
(note the plural) collection.
No Ben, i was used my own collection without importing. Thanks, i understand now
How about how to embed or link one schema with others. Could you please give us more example how to go down deep with mongoose would be nice.
I would love to know what is the best way to embed/link such schema in one collection.
Thanks for the suggestion, Pruyta. I will try to integrate that into the next set of lessons.
Thanks for the great course Ben! Finding it super helpful in brushing off the cobwebs, hadn't set up an Express server by hand in a while.
For those doing this course in 2020, I personally haven't found it too hard to work out what's been deprecated since the course was created, and using X replacement instead. Figured I'd paste my db.js
code, which has a few subtle tweaks from what Ben describes, in case it helps anyone:
var uri = "mongodb://localhost:27017" // standard mongo port
var MongoClient = require("mongodb").MongoClient;
var findUsers = function (db, callback) {
var cursor = db.collection("users").find();
cursor.each(function (err, doc) {
if (doc !== null) {
console.dir(doc)
} else {
callback()
}
})
}
MongoClient.connect(uri, function (err, client) {
var db = client.db("test"); // "test" is the name of our DB
findUsers(db, function () {
client.close();
})
})