无法在node.js中使用mongoose查询mongoDB

时间:2012-12-22 13:12:16

标签: node.js mongodb mongoose

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

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

然后我希望通过以下代码在node.js中使用mongoose进行查询:

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

但它没有给我任何回报

我的代码有什么问题?如何获得正确的查询结果?

4 个答案:

答案 0 :(得分:6)

在确定要使用的集合名称时,Mongoose会对小写的模型名称进行复数化。因此,如果模型名称为'Co',则默认情况下会在cos集合中查找。

覆盖默认设置并与现有的co集合对齐:

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

答案 1 :(得分: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);

答案 2 :(得分:1)

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

答案 3 :(得分:1)

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

find()总是返回一个数组,所以你真的想要这个:err,docs

OR 使用findOne()

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

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

只是检查一下集合中有什么东西