猫鼬函数返回未定义

时间:2020-06-14 15:49:50

标签: node.js mongoose

由于某种原因,我的函数不断返回未定义

function checkIfExists(pid) {

    const response = Product.exists({pid: pid}, function (err, result) {
        console.log(result) // logs a boolean, the correct result that i want
        return result
    })

    return response
}

console.log(checkIfExists(123)) // returns undefined

为什么它返回未定义?

3 个答案:

答案 0 :(得分:0)

尝试在函数中更改参数“ pid”的名称。也许名字有​​冲突。

您可以记录该错误以澄清您的情况:

function checkIfExists(_pid) {
    // where _pid receive the argument
    // and pid is the field name of ur col
    const response = Product.exists({pid: _pid}, function (err, result) {
        if(err) return err
        else    return result;
    })

    return response
}

console.log(checkIfExists(123))

答案 1 :(得分:0)

猫鼬 exists 函数的定义类似于 collection.exists($ query,callback),并且不返回任何内容,这就是为什么您尚未定义。

我建议您在调用函数时使用 Promise 来获取一些东西

function checkIfExists(pid) {
 return new Promise(function(resolve, reject) {

   Product.exists({pid: pid}, function (err, result) {
    console.log(result) // logs a boolean, the correct result that i want
    resolve(result);
   })
});}

然后这样称呼它:

checkIfExists(123).then(function(response) { console.log(response); })

答案 2 :(得分:0)

Product.exists()函数将运行asynchronously,当前,您将在函数完成执行之前返回response。这就是为什么您获得undefined的原因。

一种解决方法是将回调传递给checkIfExists函数

function checkIfExists(pid, callback) {
  User.exists({ pid: pid }, callback);
}

checkIfExists(pid, function (err, result) {
  console.log(result);
});