云函数里如何随机获取数据库的一个记录的某一个字段?
发布于 6 年前 作者 fwan 2213 次浏览 来自 官方Issues

在云函数里随机获取数据库的一个记录的某一个字段,但是报错了

代码如下:

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

3 回复

我这样打印是没问题的console.log(“中文”,word)

但是我如果变成这样就报错了

console.log(“中文”,word.data[0].chs)

就是这个: Cannot read property ‘0’ of undefined

这个要怎么取出一个字段的信息?

语法错误吧?

await怎么还有then?

let word = await db.collection('word').aggregate().sample({size: 1}).end()

console.log("中文",word.data[0].chs)

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 })
回到顶部