mongoose返回的数据解构失败.
业务场景1: 自定义返回的数据格式
async function testPromise() {
const promiseName = new Promise(resolve => {
resolve({ name: 'xiaobe' });
});
const promiseAge = new Promise(resolve => {
resolve({ age: '22' });
});
const result = await Promise.all([promiseName, promiseAge]);
const [name, age] = result;
// return result;
return {
...name,
...age,
};
}
async function test() {
const res = await testPromise();
console.log('res', res);
}
test()
/**
* 输出:
* res { name: 'xiaobe', age: '22' }
*/
业务场景2: 返回mongoose查询mongodb返回的数据
// mongodb数据库数据格式
{
"_id": ObjectId("5de62a3aa1b4c42f7fb66d05"),
"currentProgress": 10
}
// 获取数据
function fetchClockDay() {
return new Promise((resolve, reject) => {
ClockDayModel.findOne({}, { _id: 0 }, (err, res) => {
if (err) {
reject(err);
}
resolve(res); // 返回格式为{ "currentProgress": 10 }
});
});
}
// 请求
async function fetch() {
const result = await Promise.all([
fetchDailyDoneNum(),
fetchDailyDoneProgress(),
fetchClockDay(),
]);
const [doneNum, doneProgress, clockDay] = result;
return { doneNum, doneProgress, ...clockDay };
}
/**
* 输出:
* res { doneNum: { doneTaskNum: 10, allTaskNum: 100 },
doneProgress: { currentProgress: 10 },
'$__':
InternalCache {
strictMode: true,
selected: { _id: 0 },
shardval: undefined,
saveError: undefined,
validationError: undefined,
adhocPaths: undefined,
removing: undefined,
inserting: undefined,
saving: undefined,
version: undefined,
getters: {},
_id: undefined,
populate: undefined,
populated: undefined,
wasPopulated: false,
scope: undefined,
activePaths:
StateMachine { paths: {}, states: [Object], stateNames: [Array] },
pathsToScopes: {},
cachedRequired: {},
session: undefined,
'$setCalled': Set {},
ownerDocument: undefined,
fullPath: undefined,
emitter:
EventEmitter {
_events: [Object: null prototype] {},
_eventsCount: 0,
_maxListeners: 0 },
'$options': { skipId: true, isNew: false, willInit: true } },
isNew: false,
errors: undefined,
_doc: { clockDay: 10 },
'$locals': {},
'$init': true }
*/
解构部分数据被转换,不清楚是因为什么?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
实际上mongoose返回的数据并不是object,虽然通过typeof判断类型是Object,但其实mongoose自己封装的一个对象,并且这个对象会对数据进行实时查询以保证其符合预定义的model,而无论添加删除model都不会改变,所以设置无效。
在返回的result对象调用
toObject()
或toJSON()
方法,则可以对它进行修改。