首页 > 解决方案 > 想检查用户是否已经存在 MongoDB

问题描述

我的承诺总是拒绝即使我传入参数的_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!")
                }
            }
            )
        });
    };

标签: javascriptnode.jsmongodbpromise

解决方案


如果找到数据并拒绝承诺,您必须解决承诺。我在下面更正了您的代码:

    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!")
                }
            }
            )


推荐阅读