在云函数里随机获取数据库的一个记录的某一个字段,但是报错了
代码如下:
let word = await db.collection('word')
.aggregate()
.sample({
size: 1
})
.end()
// .then(res => {console.log("随机数结果",res.data[0].eng,res.data[0].chs); })
.then(res => { console.log("随机数结果", res); })
.catch(err => {console.log("随机数错误",err); })
console.log("中文",word.data[0].chs)
返回结果:
{"errorCode":1,"errorMessage":"user code exception caught","stackTrace":"Cannot read property 'data' of undefined"}
日志:
START RequestId: f2f88334-f188-11e9-aabf-525400697544
Event RequestId: f2f88334-f188-11e9-aabf-525400697544
2019-10-18T09:23:30.696Z f2f88334-f188-11e9-aabf-525400697544 随机数结果 { list: [ { _id: 'XakbZfdsX1oQevCz', chs: '钢笔', eng: 'pen' } ],
errMsg: 'collection.aggregate:ok' }
TypeError: Cannot read property 'data' of undefined
at EventHandler.exports.main [as realHandler] (/var/user/index.js:28:27)
at <anonymous>
at process._tickCallback (internal/process/next_tick.js:188:7)
END RequestId: f2f88334-f188-11e9-aabf-525400697544
Report RequestId: f2f88334-f188-11e9-aabf-525400697544 Duration:38ms Memory:256MB MaxMemoryUsed:30.636719MB
语法错误吧?
await怎么还有then?
let word = await db.collection('word').aggregate().sample({size: 1}).end()
console.log("中文",word.data[0].chs)
我这样打印是没问题的console.log("中文",word)
但是我如果变成这样就报错了
console.log("中文",word.data[0].chs)
就是这个: Cannot read property '0' of undefined
这个要怎么取出一个字段的信息?
2019-10-18T09:23:30.696Z f2f88334-f188-11e9-aabf-525400697544 随机数结果 { list: [ { _id: 'XakbZfdsX1oQevCz', chs: '钢笔', eng: 'pen' } ],
结果已经出来了,显然是代码问题,这里没返回值
.then(res => { console.log(
"随机数结果"
, res); })
.then(res => { console.log(
"随机数结果"
, res);
return
res })
let word = await db.collection('word')
.aggregate()
.sample({
size: 1
})
.end()
// .then(res => {console.log("随机数结果",res.data[0].eng,res.data[0].chs); })
.then(res => { console.log("随机数结果", res); return res})
.catch(err => {console.log("随机数错误",err); })
console.log("中文",word.data[0].chs)
日志如下:
START RequestId: 3338ea66-f2eb-11e9-9949-525400e24e59
Event RequestId: 3338ea66-f2eb-11e9-9949-525400e24e59
2019-10-20T03:39:20.316Z 3338ea66-f2eb-11e9-9949-525400e24e59 随机数结果 { list: [ { _id: 'XakbP0_Mv-8c5-iR', chs: '苹果', eng: 'apple' } ],
errMsg: 'collection.aggregate:ok' }
TypeError: Cannot read property '0' of undefined
at EventHandler.exports.main [as realHandler] (/var/user/index.js:26:31)
at
at process._tickCallback (internal/process/next_tick.js:188:7)
END RequestId: 3338ea66-f2eb-11e9-9949-525400e24e59
Report RequestId: 3338ea66-f2eb-11e9-9949-525400e24e59 Duration:28ms Memory:256MB MaxMemoryUsed:34.648438MB