I want transform original array stored with id of departments, pushing object document to same array. But when execute got "Converting circular structure to JSON".
Any idea how get all object document referenced by id and after replace the same array?
I create a Mutations.js for manage my functions transform JSON like remove _id to id and add href key with API url.
But first I want add departments object document to department key in original JSON.
Controller User
const boom = require('boom')
const User = require('../models/Users')
const Departments = require('../models/Departments')
const Mutation = require('../mutations')
// GET all users
exports.getUsers = async (req, reply) => {
try {
const users = await User.find()
var json = [];
users.map(item => {
var element = Mutation.toJSON( item.toObject({ versionKey: false }) );
element.departments = Mutation.rebuildArray(Departments, item.departments)
json.push(element);
})
return json
} catch (err) {
throw boom.boomify(err)
}
}
Mutation.js
//Here convert document to JSON with structure needed
const toJSON = document => {
document.id = document._id;
delete document._id;
return document;
}
//Create a array with document searched by id
const rebuildArray = (model, array) => {
var newArray = [];
array.map(item => {
var element = model.findById(item);
newArray.push(toJSON(element));
})
return newArray;
}
exports.rebuildArray = buildArray;
exports.toJSON = toJSON;
exports.addURL = addURL;
I want recieve this JSON for example:
[
{
"id": "f98nu4505fd782"
"firstname": "John",
"lastname": "Doe",
"departments": [
{
"id": "d8nn83873434",
"name": "Department 1 Name"
},
{
"id": "9d8n892030e9",
"name": "Department 2 Name"
}
]
}
]
With this original JSON:
[
{
"id": "f98nu4505fd782"
"firstname": "John",
"lastname": "Doe",
"departments": ["d8nn83873434","9d8n892030e9"]
}
]
Thanks!
You should try to use .populate('departments') of mongoose query.
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加