【问题标题】:Can't query mongoDB with mongoose in node.js无法在 node.js 中使用 mongoose 查询 mongoDB
【发布时间】:2012-12-09 19:11:45
【问题描述】:

假设我的 mongoDB 中有一个集合:db.co 并且只有一份文件:

{ "_id" : ObjectId("50d083e32cdcf7ce065b616c"), 
  "age" : 22, 
  "friends" : [ "Tom"], 
  "location" : "NY", 
  "name" : "lee", 
  "skill" : [ "javascript", "java" ] 
 }

然后我想通过此代码在node.jsmongoose 中查询它:

var coSchema = mongoose.Schema( {
    age: Number,
    friends: Array, 
    location: String,
    name: String,
    skill: Array
})

var Co = mongoose.model('Co', coSchema);
function findSomeoneInCo (name) {
  Co.find({"name": name}, function (err, doc) {
    if (err) {
        console.log('find some one failed: ' + err);
        return;
    }
    console.log('find successed: ' + doc);
  })
}

findSomeoneInCo("lee");

但它什么也没给我

我的代码有什么问题?怎样才能得到正确的查询结果?

【问题讨论】:

标签: node.js mongodb mongoose


【解决方案1】:

Mongoose 在确定要使用的集合名称时将小写的模型名称复数。因此,如果模型名称为 'Co',它将默认在 cos 集合中查找。

要覆盖默认值并与您现有的 co 集合对齐:

var Co = mongoose.model('Co', coSchema, 'co');

【讨论】:

    【解决方案2】:

    Mongoose 在任何 CURD 操作期间都会使您的模型名称复数, 使用这个并检查:

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

    var coSchema = new Schema({
        age: Number,
        friends: Array, 
        location: String,
        name: String,
        skill: Array
    }, {collection:'co'});
    var Co = mongoose.model('Co',coSchema);
    

    【讨论】:

      【解决方案3】:

      .find() 异步工作,这意味着它的回调在你的函数已经有的时候运行。

      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);
      });
      

      【讨论】:

      • 我试过这种方式,但是没有成功。其实第一种方式不用回调,可以查询另一个集合的数据。就可以查询这个
      【解决方案4】:

      我注意到你对 find() 的回调有以下参数:err, doc

      find() 总是返回一个数组,所以你真的希望它是:err, docs

      或 使用 findOne()

      在您发布的代码中,异步内容不应该是问题,嵌套的回调仍然会被执行。你确定你的连接没问题。我会运行一个开放式查询:

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

      只是为了检查集合中有什么东西

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-08-10
        • 1970-01-01
        • 2012-02-07
        • 2015-09-20
        • 2011-12-07
        • 1970-01-01
        • 2016-06-03
        • 1970-01-01
        相关资源
        最近更新 更多