How to use mongoose findOne

前端 未结 5 1648
死守一世寂寞
死守一世寂寞 2020-12-01 07:32

I have the below schema (apologies that it is in coffeescript)

Schema = mongoose.Schema

AuthS = new Schema
    auth:   {type: String, unique: true}
    nick         


        
相关标签:
5条回答
  • 2020-12-01 07:48

    Mongoose basically wraps mongodb's api to give you a pseudo relational db api so queries are not going to be exactly like mongodb queries. Mongoose findOne query returns a query object, not a document. You can either use a callback as the solution suggests or as of v4+ findOne returns a thenable so you can use .then or await/async to retrieve the document.

    // thenables
    Auth.findOne({nick: 'noname'}).then(err, result) {console.log(result)};
    Auth.findOne({nick: 'noname'}).then(function (doc) {console.log(doc)});
    
    // To use a full fledge promise you will need to use .exec()
    var auth = Auth.findOne({nick: 'noname'}).exec();
    auth.then(function (doc) {console.log(doc)});
    
    // async/await
    async function auth() {
      const doc = await Auth.findOne({nick: 'noname'}).exec();
      return doc;
    }
    auth();
    
    

    See the docs if you would like to use a third party promise library.

    0 讨论(0)
  • 2020-12-01 07:48

    In my case same error is there , I am using Asyanc / Await functions , for this needs to add AWAIT for findOne

    Ex:const foundUser = User.findOne ({ "email" : req.body.email });
    

    above , foundUser always contains Object value in both cases either user found or not because it's returning values before finishing findOne .

    const foundUser = await User.findOne ({ "email" : req.body.email });
    

    above , foundUser returns null if user is not there in collection with provided condition . If user found returns user document.

    0 讨论(0)
  • 2020-12-01 07:53

    Found the problem, need to use function(err,obj) instead:

    Auth.findOne({nick: 'noname'}, function(err,obj) { console.log(obj); });
    
    0 讨论(0)
  • 2020-12-01 07:53

    Use obj[0].nick and you will get desired result,

    0 讨论(0)
  • 2020-12-01 07:54

    You might want to consider using console.log with the built-in "arguments" object:

    console.log(arguments); // would have shown you [0] null, [1] yourResult
    

    This will always output all of your arguments, no matter how many arguments you have.

    0 讨论(0)
提交回复
热议问题