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

How to return a complex json response with node js

1个答案

1

In Mongoose, you can save complex JSON data by defining a schema. A schema in Mongoose defines the structure and data types of documents. When saving nested JSON objects, you can use nested documents (subdocuments) or the Mixed type within the schema.

Using Subdocuments

If the JSON structure is known and you want to nest objects within it, define subdocuments in the schema.

javascript
const mongoose = require('mongoose'); const { Schema } = mongoose; // Subdocument schema const childSchema = new Schema({ name: String, age: Number }); // Parent document schema const parentSchema = new Schema({ children: [childSchema], // Array of subdocuments name: String }); // Create model const Parent = mongoose.model('Parent', parentSchema); // Create an instance with nested subdocuments const parent = new Parent({ name: 'John Doe', children: [{ name: 'Jane Doe', age: 10 }, { name: 'Jack Doe', age: 8 }] }); // Save instance parent.save(function (err) { if (err) return handleError(err); // Saved successfully });

Using Mixed Type

If the JSON data structure is not fixed or very complex, use Schema.Types.Mixed to save data of any type.

javascript
const mongoose = require('mongoose'); const { Schema } = mongoose; // Define schema with Mixed type const anySchema = new Schema({ any: Schema.Types.Mixed }); // Create model const AnyModel = mongoose.model('Any', anySchema); // Create an instance with complex JSON data const anyData = new AnyModel({ any: { someField: 'value', nested: { complex: ['data', { can: 'be' }, 'anything'], you: 'like' } } }); // Save instance anyData.save(function (err) { if (err) return handleError(err); // Saved successfully });

When using the Mixed type, note that Mongoose does not automatically track changes to this type. Therefore, if you modify data within a Mixed type field, manually call .markModified(path) to inform Mongoose that the field has been modified.

javascript
anyData.any.nested.complex.push('new data'); anyData.markModified('any'); anyData.save(function (err) { if (err) return handleError(err); // Saved updated data });

Summary

Saving complex JSON data in Mongoose typically involves defining a schema that accurately reflects the data structure. Use nested documents for data with a known structure or the Mixed type for data that is not fixed or very complex. Remember to call .markModified() after modifying Mixed type fields to ensure proper saving.

2024年6月29日 12:07 回复

你的答案