Mongoose Schemas Aliases
Last Updated :
02 Nov, 2022
Mongoose is a MongoDB object modeling and handling for a node.js environment. Mongoose Schemas Aliases help in converting a short property name in the database into a longer, more verbal, property name to enhance code readability.
Creating node application And Installing Mongoose:
Step 1: Create a node application using the following command:
mkdir folder_name
cd folder_name
npm init -y
Step 2: After creating the ReactJS application, Install the required module using the following command:
npm install mongoose
Project Structure: It will look like the following.
Example 1: In this example, we will create a “name” alias for the “n” property in mongoose schema.
Filename: main.js
Javascript
const mongoose = require( 'mongoose' )
dbName: 'event_db' ,
useNewUrlParser: true ,
useUnifiedTopology: true
}, err => err ? console.log(err) :
console.log( 'Connected to database' ));
const personSchema = new mongoose.Schema({
n: {
type: String,
alias: 'name'
}
});
const Person = mongoose.model( 'Person' , personSchema);
const person = new Person({ name: 'Val' });
console.log(person);
|
Step to Run Application: Run the application using the following command from the root directory of the project:
node main.js
Output:
Example 2: In this example, we will create “first” and “last” aliases for the properties “f” and “l”, respectively, in the mongoose schema.
Filename: main.js
Javascript
const mongoose = require( 'mongoose' )
dbName: 'event_db' ,
useNewUrlParser: true ,
useUnifiedTopology: true
}, err => err ? console.log(err) :
console.log( 'Connected to database' ));
const personSchema = new mongoose.Schema({
f: {
type: String,
alias: 'first'
},
l: {
type: String,
alias: 'last'
}
});
const Person = mongoose.model( 'Person' , personSchema);
const person = new Person({ first: 'Hello' , last: 'World' });
console.log(person);
|
Step to Run Application: Run the application using the following command from the root directory of the project:
node main.js
Output:
Reference: https://mongoosejs.com/docs/guide.html#aliases
Share your thoughts in the comments
Please Login to comment...