javascript - 想要检查用户是否已经存在 MongoDB

标签 javascript node.js mongodb promise

我的 promise 总是拒绝,即使我传入参数的_name并不总是与集合中的名称相同,任何帮助将不胜感激 谢谢!

    myCheckUser(_name) {
        var self = this;
        return new Promise((resolve, reject) => {
            self.db.collection("USER").find({ "username": _name }, { $exists: true }).toArray(function    (err, doc) //find if a value exists
            {
                console.log("DOC USERNAME: " + doc.username);
                if (doc) //if it does
                {
                    reject("Found user");
                    console.log(doc.username); // print out what it sends back
                }
                else // if it does not 
                {
                    console.log("Not in docs");
                    resolve("Not found continue logic!")
                }
            }
            )
        });
    };

最佳答案

如果找到数据,您必须解决 promise 并拒绝 promise 。我已更正您的代码如下:

    myCheckUser(_name) {
        var self = this;
        return new Promise((resolve, reject) => {
            self.db.collection("USER").find({ "username": _name }, { $exists: true }).toArray(function    (err, doc) //find if a value exists
            {
                if (doc && doc.length) //if it does
                {
                    console.log(doc); // print out what it sends back
                    resolve("Found user");
                }
                else // if it does not 
                {
                    console.log("Not in docs");
                    reject("Not found continue logic!")
                }
            }
            )

关于javascript - 想要检查用户是否已经存在 MongoDB,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55149008/

相关文章:

node.js - 是否有用于 JavaScript 的 LUA 之类的脚本语言?

node.js - 类型错误 : Cannot read property 'find' of undefined on mongoose

java - 在 Morphia 中使用 transient

javascript - 考虑到内部元素的边距,如何获得 DIV 的高度?

javascript - 如何使用购物车收藏

javascript - AJAX调用后如何制作弹出框动画?

javascript - 将 Blob 数据转换为 javascript 或 Node 中的原始缓冲区

node.js - 在 Mongoose 中定义数组的首选方法是什么?

javascript - 不循环遍历 'click' 上的 img .src 更改

javascript - 如何为动态表单字段设置initialValue( Ant 设计)?