# xpress-mongo - Documentation
Npm (opens new window) | Git (opens new window) | Change Logs
xpress-mongo is a light mongodb model/helper library for nodejs that provides modeling for your documents while keeping you very close to mongodb native syntax which is always Recommended.
For Example.
Model.native().findOne({}) // Mongodb native query
The .native()
model instance method allows you run raw mongodb native queries.
# Menu
# Installation
Using Package Managers.
# Connection
# Quick Example
create a file xmongo.js
const { Client, XMongoModel } = require("xpress-mongo");
// Your Model extends a class for your collection
// Should probably exist in a separate file
class User extends XMongoModel {
static collectionName = "users";
/**
* Returns the full name of the user.
* @return {string}
*/
fullName() {
return this.data.firstName + " " + this.data.lastName;
}
}
async function run() {
// Initialise connection
const connection = Client("mongodb://127.0.0.1:27017", {
useNewUrlParser: true,
useUnifiedTopology: true
});
try {
// Try Connecting
await connection.connect();
// Set Database name
connection.useDb("xmongo");
console.log("Connected to mongodb");
} catch (e) {
throw e;
}
connection.linkModel(User);
// Find one user in users collection
let user = await User.findOne({});
// If user is found
if (user) {
// Log user and full name
console.log(user);
console.log(`Fullname: ${user.fullName()}`);
} else {
console.log("No user found, creating one....");
// Create new user
user = await User.new({
firstName: "John",
lastName: "Doe"
});
// Log user data and full name
console.log(user);
console.log(`FirstName: ${user.fullName()}`);
}
}
run().catch(console.log);
Run the above code, check your database to see if a user was created. After that go through the codes.
# Line 5-8
The Client
imported from xpress-mongo is being initialised providing Mongodb connection string and options
# Line 11-20
Try connecting to the mongo server on Line 13 and after that we set the database name.
# Line 23-32
These lines shows a basic xpress-mongo Model class for the collection named users.
The User
class extended a class generated by xpress-mongo for the collection users.
The fullName
method in the User
class shows a basic example of a Model method and how data is accessed from the
model instance.
# Line 35-56
On Line 35 a static method of the model class User
is used to findOne
document in the collection.
The FindOne
method returns an instance of the User model or null
if no results.
On Line 47 a new user is created using xpress-mongo new
static method
# CRUD Example
Create, Read, Update, and Delete (CRUD) are the four basic functions that models should be able to do, at most.
# Create a new document
There are two ways to create a document in a collection, Instant or Buildup
// Instant
const user = await User.new({
email: 'john@doe.com',
firstName: 'John',
lastName: 'Doe'
});
// Buildup
const user = new User();
// set single field
user.set('email', 'john@doe.com');
// set multple fields
user.set({
firstName: 'John',
lastName: 'Doe'
});
await user.save();
# Read document
// Find all, @returns Arrays
const users = await User.find({verified: true});
// Find One, @returns Model instance
const user = await User.findOne({email: 'john@doe.com'});
// Find by Id, @returns Model instance
const user = await User.findById('ObjectID or ObjectID-string');
// Log result.
console.log(user)
User {
data: {
_id: ObjectID,
email: "john@doe.com",
firstName: "John",
lastName: "Doe"
}
}
# Update Document
You can update a model instance document either by using the buildup or instant method.
const user = await User.findOne({email: 'john@doe.com'});
// Build Up
user.set('middleName', 'Donald') // set middleName
await user.save(); // save to database
// Instant
await user.update({middleName: 'Donald'});
# Delete Document
const user = await User.findOne({email: 'john@doe.com'});
// Delete document
await user.delete();