Mongoose Schematype.cast()函数

Mongoose Schematype.cast()函数

Mongoose 是用于node.js环境的MongoDB对象建模和处理工具。 Mongoose.SchemaType.cast() 是Mongoose提供的方法,用于将一个值转换为Mongoose模式中定义的适当类型。让我们通过一些示例更加了解这个方法。

语法:

mongoose.datatype.cast( function(){})

参数:

  • datatype: 它是要将数据转换为的数据类型。
  • function: 这是一个使用一些逻辑并返回所需数据类型的函数。

返回类型: 它返回一个将强制转换为数据类型的匿名函数。

创建Node应用程序并安装Mongoose:

步骤1: 使用以下命令创建一个Node应用程序:

mkdir folder_name
cd folder_name
npm init -y
touch main.js

步骤2: 在创建应用程序之后,请使用以下命令安装所需的模块:
Advertisement

npm install mongoose

项目结构: 它将类似于下面的样子。

Mongoose Schematype.cast()函数

示例1: 在此示例中,我们将使用mongoose中的cast函数,并将person Schema的age属性强制转换为字符串。

文件名: script.js

const mongoose = require('mongoose');
let Schema = mongoose.Schema;
 
mongoose.Number.cast(v => {
    if (typeof v === 'number') { return '30' }
})
let personSchema = new Schema({
    name: String,
    age: Number
});
let Person = mongoose.model('Person', personSchema);
 
let person = new Person({
    name: 'John Doe',
    age: 30
});
console.log('Type of Age is : ', typeof person.age);

运行应用的步骤: 从项目的根目录中使用以下命令运行应用:

node script.js

输出:

Mongoose Schematype.cast()函数

示例2: 在这个示例中,我们将在模式中的”age”属性中设置转换函数,并将该属性转换为数字类型。

文件名: script2.js

const mongoose = require('mongoose');
const Schema = mongoose.Schema;
 
let personSchema = new mongoose.Schema({
    name: String,
    age: {
        type: Number,
        cast: function castAge(v) {
            if (typeof v === 'number') {
                return v;
            }
            if (typeof v === 'string' && !isNaN(v)) {
                return +v;
            }
            if (v instanceof Date) {
                return Math.floor((Date.now() - v) /
                    (1000 * 60 * 60 * 24 * 365));
            }
        }
    }
});
 
let Person = mongoose.model('Person', personSchema);
 
let person = new Person({
    name: 'John Doe',
    age: new Date('2001/01/30')
});
console.log('Type of Age is : ', typeof person.age);
console.log('Age of Person is :', person.age);

运行应用程序的步骤: 在项目的根目录中使用以下命令来运行应用程序:

node script2.js

输出结果:

Mongoose Schematype.cast()函数

参考: https://mongoosejs.com/docs/api/schematype.html#schematype_SchemaType-cast

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程