我要转换存储有部门ID的原始数组,将目标文档推送到同一数组。但是执行时出现“将循环结构转换为JSON”。
有什么主意,如何获取ID引用的所有对象文档并替换相同的数组之后?
我创建了一个Mutations.js来管理我的函数,将JSON转换为删除_id到id并使用API url添加href键。
但是首先我想将部门对象文档添加到原始JSON中的部门密钥中。
控制器用户
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
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)
}
}
例如,我想接收此JSON:
//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;
使用此原始JSON:
//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;
谢谢!