当前位置: 首页>>编程示例 >>用法及示例精选 >>正文


Mongoose Document.prototype.toJSON()用法及代码示例

Mongoose 文档API.prototype.toJSON()方法Mongoose API 的一部分用于文档模型。它允许将结果集转换为 JSON 对象。转换后的 JSON 对象可以用作参数JSON.stringify()方法。让我们了解一下toJSON()使用示例的方法。

用法:

document.toJSON( options );

参数:该方法接受单个参数,如下所述:

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

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

设置 Node.js 应用程序:

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

npm init

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

npm install mongoose

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

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

示例 1:在此示例中,我们将说明以下函数toJSON()方法。我们正在使用该方法将结果集转换为 JSON 对象。

文件名:app.js

Javascript


// 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

Javascript


// 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



相关用法


注:本文由纯净天空筛选整理自kartikmukati大神的英文原创作品 Mongoose Document.prototype.toJSON() API。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。