Mongoose Document.prototype.toJSON()函数

Mongoose Document.prototype.toJSON()函数

The Mongoose Document API.prototype.toJSON()方法 用于Document模型。它允许将结果集转换为JSON对象。然后可以将转换后的JSON对象用作 JSON.stringify() 方法的参数。让我们通过一个示例来了解 toJSON() 方法。

语法:

document.toJSON( options );

参数: 此方法接受以下讨论参数:

  • options: 用于配置方法的各种属性。

返回值: 此方法返回JavaScript JSON对象。

设置Node.js应用程序:

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

npm init

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

npm install mongoose

项目结构: 项目的结构将如下所示:

Mongoose Document.prototype.toJSON()函数

数据库结构:

数据库结构将如下所示,以下文档存在于集合中。

Mongoose Document.prototype.toJSON()函数

示例1: 在这个示例中,我们演示了 toJSON() 方法的功能。我们使用该方法将结果集转换为JSON对象。

文件名:app.js

// Require mongoose module 
const mongoose = require("mongoose"); 
  
// Set Up the Database connection 
const URI = "mongodb://localhost:27017/geeksforgeeks"; 
  
const connectionObject = mongoose.createConnection(URI, { 
    useNewUrlParser: true, 
    useUnifiedTopology: true, 
}); 
  
const Customer = connectionObject.model( 
    "Customer", 
    new mongoose.Schema({ 
        name: String, 
        address: String, 
        orderNumber: Number, 
    }) 
); 
  
Customer.findById("639ede899fdf57759087a655").then(res => { 
    const jsonObject = res.toJSON(); 
    console.log(jsonObject) 
}).catch(err => { 
    console.log(err); 
})

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

node app.js

输出:

{
  _id: new ObjectId("639ede899fdf57759087a655"),
  name: 'Chintu',
  address: 'IND',
  orderNumber: 9,
  __v: 0
}

示例2: 在这个示例中,我们展示了toJSON()方法的功能。我们将结果转换为JSON对象,然后再使用JSON.stringify()方法将其转换为字符串。最后,我们显示了转换后的两个值的类型。

文件名:app.js

// Require mongoose module 
const mongoose = require("mongoose"); 
  
// Set Up the Database connection 
const URI = "mongodb://localhost:27017/geeksforgeeks"; 
  
const connectionObject = mongoose.createConnection(URI, { 
    useNewUrlParser: true, 
    useUnifiedTopology: true, 
}); 
  
const customerSchema = new mongoose.Schema({ 
    name: String, 
    address: String, 
    orderNumber: Number, 
}) 
  
const Customer = connectionObject.model( 
    "Customer", customerSchema 
); 
  
customerSchema.set('toJSON', { virtuals: true }); 
  
Customer 
    .findById("639ede899fdf57759087a655") 
    .exec((error, result) => { 
        if (error) { 
            console.log(error); 
        } else { 
            console.log(typeof result); 
            const jsonObject = result.toJSON(); 
            const stringConverted = JSON.stringify(jsonObject); 
            console.log(typeof stringConverted); 
        } 
    });

运行程序的步骤: 要运行应用程序,请从项目的根目录执行以下命令:

node app.js

输出:

object
string

参考: https://mongoosejs.com/docs/api/document.html#document_Document-toJSON

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程