Skip to main content

Posts

Showing posts with the label mongo

Connecting to MongoDB from WSL2

My application runs a web server connected to a MongoDB database. For all my development needs, I am using WSL on windows 10. Unfortunately, MongoDB is not available on WSL, so I have installed the Windows version and pointed my server to the localhost:27017 address, no issue. It worked well until the day I switched to WSL2. Then I would get some ECONNREFUSED errors. To solve this problem, I have found a simple three steps solution.  The whole idea is that WSL2 now uses a true VM and got its own network interface (IP, MAC address, etc.). I think it's a bit more complicated than that, but that's how I understand it. Long story short, you now have a windows IP, and a WSL IP. 1. Accessing  the windows host from WSL The first step is to make sure that you can ping the windows IP from WSL. It was not working for me right away. It seems like there are still inconsistencies in the WSL implementation, but this github issue thread gave a good solution. It's a script yo have to run...

Filter Documents' Attributes in a Mongoose Query

 Sometimes we don't want to display the full object stored in mongo to our user. One way of handling this is to query all the relevant documents, iterate on all of them programmatically and filter out all the unwanted attributed. Coming from a SQL world, I prefer to let the database engine do the work for me. It turns out it's quite easy to do using mongoose. Indeed, the find() method of a model accepts a second string parameter. This string must contain the name of all the attributes you want to keep . Note that the separator is a space. This would be the syntax: const xyzArticles = await Article.find({userUuid:"XYZ"}, "title content authorBio"); Source from the mongoose package documentation

How to Enforce Type Validation in a Mongoose Schema

Before running the actual validation functions, mongoose will try to cast the model's value into their type declared in the schema. If the cast operation is successful, then mongoose continues to the actual validation steps. As a result, it means that if one your value is a number that can be casted to a string, then the validation will succeed!  Most of the time it's probably fine, however if it's a problem for you, the set function is a lot of help: const schema = new mongoose.Schema({  mustBeAString: {   type: String,   required: true,   set: function (v) {    let validType = typeof v === "string" || v instanceof String;    if (validType) {     return v;    } else {     throw new Error("invalid type");    }   },  }, }); This way you can be sure that the value was a string from the start. I have found this tip in this stackoverflow ticket , and then changed the code a l...

How to Progamatically Validate a Mongoose Model Instance

When using built-in validations in a mongoose model, it's possible to trigger a model validation. For example if you received user inputs, and created a new instance of your model, well it's possible to make sure the models fits your needs. It's pretty convenient if you want to make sure that what you are going to insert fits your requirements without actually querying the database server. let user = new User({username:"jack", age:38}); await user.validate(); Sources from the mongoose package documentation: Built-in validators The Validate method

How to Setup MongoDb Access Control

When installed for the first time, there is no access control by default. To activate it, one must connect to the unprotected instance and create a new admin user like this: db . createUser ( { user : "myUserAdmin" , pwd : passwordPrompt (), // or cleartext password roles : [ { role : "userAdminAnyDatabase" , db : "admin" }, "readWriteAnyDatabase" ] } )  Then restart the mongo process, either through the command line or db . adminCommand ( { shutdown : 1 } ) Source from the mongodb documentation, for mongo 4.4