乐闻世界logo
搜索文章和话题

How to get array of json objects rather than mongoose documents

1个答案

1

When querying a MongoDB database using Mongoose, by default, query operations return an array of document instances. Each document is an instance of its corresponding model, holding data saved to MongoDB and a series of methods (such as .save() and .remove()).

If you want to directly obtain a plain JSON object array instead of document instances, you can use the .lean() method. The .lean() method instructs Mongoose to skip instantiating fully-featured documents and instead return plain JavaScript objects, which can improve query performance.

Below is an example using the .lean() method:

javascript
const mongoose = require('mongoose'); const { Schema } = mongoose; // Define a Mongoose model const userSchema = new Schema({ name: String, age: Number, email: String }); const User = mongoose.model('User', userSchema); // Connect to MongoDB database mongoose.connect('mongodb://localhost:27017/mydatabase'); // Use .find() to query and use .lean() to return a plain JSON object array User.find({}).lean().exec((err, users) => { if (err) { throw err; } // `users` will be an array containing plain JSON objects console.log(users); });

In the above code, by adding .lean() to the .find() method chain, the users variable will be an array of plain JSON objects containing multiple user data, rather than an array of Mongoose document instances. Using .lean() can improve query efficiency, especially when only reading data without needing to perform data operations.

2024年6月29日 12:07 回复

你的答案