[英]How to save the return from Mongoose exec function?
I am trying to save the return from the following function:我正在尝试保存以下 function 的返回:
let maxNum;
const result = Url.find({})
.sort({short_url: - 1})
.select('short_url')
.exec((err, data) => {
console.log('what is data', data)
if (err) return console.log(err);
console.log('what is data here', data[0].short_url)
maxNum = data[0].short_url;
});
console.log("resultsssss", result);
console.log('give me maxnum', maxNum);
What I am getting back is:我得到的是:
resultsssss undefined
give me maxnum undefined
what is data [ { _id: 5ed434038de5842a1b14c44d, short_url: 2 },
{ _id: 5ed432937439e628e98e43e4, short_url: 1 },
{ _id: 5ed57d1dbd11721236587e2b } ]
what is data here 2
You can see if I log inside the exec then I get the data but I can't get the whole thing outside of that and keeps giving me undefined.您可以查看我是否在 exec 中登录,然后我会获取数据,但我无法获得除此之外的全部内容,并且一直给我未定义的信息。 How can I get the data so I can save it to a variable outside of this function?如何获取数据以便将其保存到此 function 之外的变量中?
your promise doesn't return the result you have to add somthing like .then(if(user){return user})
你的 promise 不返回结果你必须添加类似.then(if(user){return user})
The exec
call is asynchronous so by the time you console.log, the function has not completed running yet. exec
调用是异步的,因此当您使用 console.log 时,function 尚未完成运行。
Simply move your console.log into the callback of the exec
call.只需将您的 console.log 移动到exec
调用的回调中。
let maxNum;
const result = Url.find({})
.sort({short_url: - 1})
.select('short_url')
.exec((err, data) => {
if (err) return console.log(err);
console.log('what is data', data)
console.log('what is data here', data[0].short_url)
maxNum = data[0].short_url;
console.log('give me maxnum', maxNum);
});
or use await
statement:或使用await
语句:
const result = await Url.find({})
.sort({short_url: - 1})
.select('short_url')
.exec();
// access whatever you need
const maxNum = result[0].short_url;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.