Mongoose SchemaType.prototype.text()函数

Mongoose SchemaType.prototype.text()函数

Mongoose 是用于MongoDB的对象数据建模(ODM)库。它定义了一个强类型的模式,具有默认值和模式验证,这些验证后来被映射到MongoDB文档中。

Mongoose SchemaType API的text方法 用于根据传递给该方法的参数声明全文索引。让我们通过一些示例更加了解这个方法。

语法:

SchemaType.prototype.text()
JavaScript

参数: 它以布尔值作为输入参数。

返回类型: 它以SchemaType对象作为响应返回。

创建节点应用程序并安装Mongoose:

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

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

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

npm install mongoose
JavaScript

项目结构: 它看起来会像下面这样。

Mongoose SchemaType.prototype.text()函数

使用MongoDB Compass的GUI表示数据库: 目前,集合中没有数据。

Mongoose SchemaType.prototype.text()函数

示例1: 在此示例中,我们将使用SchemaType API的text()方法,在模式定义本身中通过分配“text”属性来在“name”路径上创建文本索引。

文件名:main.js

const mongoose = require('mongoose') 
  
// Database connection 
mongoose.connect('mongodb://localhost:27017/query-helpers', { 
    dbName: 'event_db', 
    useNewUrlParser: true, 
    useUnifiedTopology: true
}, err => err ? console.log(err) : console.log 
    ('Connected to database')); 
  
const personSchema = new mongoose.Schema({ 
    name: { 
        type: String, 
        text: true
    }, 
    age: { 
        type: Number, 
    } 
}); 
  
const personsArray = [ 
    { 
        name: 'Luffy', 
        age: 22 
    } 
] 
  
const Person = mongoose.model('Person', personSchema); 
JavaScript

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

node main.js
JavaScript

输出: 我们看到结果中的值保持不变。

Mongoose SchemaType.prototype.text()函数

使用MongoDB Compass的数据库的GUI表示:

Mongoose SchemaType.prototype.text()函数

示例2:

在这个示例中,我们将使用SchemaType API的text()方法,通过显式调用“name”路径上的“index”方法,在“name”路径上创建一个文本索引。

文件名: main.js

const mongoose = require('mongoose') 
  
// Database connection 
mongoose.connect('mongodb://localhost:27017/query-helpers', { 
    dbName: 'event_db', 
    useNewUrlParser: true, 
    useUnifiedTopology: true
}, err => err ? console.log(err) :  
    console.log('Connected to database')); 
  
const personSchema = new mongoose.Schema({ 
    name: { 
        type: String, 
    }, 
    age: { 
        type: Number, 
    } 
}); 
  
const personsArray = [ 
    { 
        name: 'Luffy', 
        age: 22 
    } 
] 
  
const Person = mongoose.model('Person', personSchema); 
personSchema.path('name').index({ text: true }) 
JavaScript

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

node main.js
JavaScript

输出: 我们可以看到结果中的值保持不变。

Mongoose SchemaType.prototype.text()函数

使用MongoDB Compass对数据库进行GUI表示:

Mongoose SchemaType.prototype.text()函数

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

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程

登录

注册