Can't query mongoDB with mongoose in node.js

前端 未结 4 1942
刺人心
刺人心 2021-01-16 03:28

Suppose I have a collection in my mongoDB: db.co and only have one document:

{ \"_id\" : ObjectId(\"50d083e32cdcf7ce065b616c\"), 
  \"age\" : 22         


        
相关标签:
4条回答
  • 2021-01-16 03:44

    .find() works asynchronous, meaning that its callback runs when your function already has.

    see variable scope in asynchronous function

    //try passing a callback function to your search function, like:
    function findSomeoneInCo (name, callback) {
    
      //happens now - here you could still return something
    
      Co.find({"name": name}, function (err, doc) {
    
       //happens later - too late to return stuff, function has ran already
    
        if (err) {
            callback(err);
            return;
        }
        callback(doc);
      })
    }
    
    
    //call your function passing a callback function
    findSomeoneInCo("lee", function(doc){
      console.log('do something with your results: ' + doc);
    });
    
    0 讨论(0)
  • 2021-01-16 03:47

    I notice your callback to find() has the following parameters : err, doc

    find() always returns an array so you really want this to be : err, docs

    OR use findOne()

    The async stuff shouldn't be a problem in the code you've posted, the nested callbacks will still be executed. Are you sure your connection is OK. I would run an open query :

    Co.find({}, function(err, docs){
     console.log(docs);
    }
    

    Just to check the collection has something in it

    0 讨论(0)
  • 2021-01-16 03:53

    Mongoose pluralizes the lower-cased model name when determining the collection name to use. So with a model name of 'Co' it's going to be looking in the cos collection by default.

    To override the default and align with your existing co collection:

    var Co = mongoose.model('Co', coSchema, 'co');
    
    0 讨论(0)
  • 2021-01-16 03:56

    Mongoose pluralizes your model name during any CURD operation, Use this & check :

    var Co = mongoose.model('Co', coSchema, 'co'); //Even the case matters
    

    or

    var coSchema = new Schema({
        age: Number,
        friends: Array, 
        location: String,
        name: String,
        skill: Array
    }, {collection:'co'});
    var Co = mongoose.model('Co',coSchema);
    
    0 讨论(0)
提交回复
热议问题