Javascript 类型错误:mongo模块';s的find方法未定义
我是NodeJS的新手,我将在MongoDB中到期。然而,我有一个在我看来非常奇怪的错误:Javascript 类型错误:mongo模块';s的find方法未定义,javascript,node.js,mongodb,Javascript,Node.js,Mongodb,我是NodeJS的新手,我将在MongoDB中到期。然而,我有一个在我看来非常奇怪的错误:TypeError:无法调用undefined的'find'方法。我试图使用节点mongo模块中的'find'方法,collection.find({id:'1},callback),但我得到的只是那个错误。然而,奇怪的是插入确实起作用。有什么问题 db.collection('users', function(error, collection) { console.log('Collection
TypeError:无法调用undefined的'find'方法。
我试图使用节点mongo模块中的'find
'方法,collection.find({id:'1},callback)
,但我得到的只是那个错误。然而,奇怪的是插入确实起作用。有什么问题
db.collection('users', function(error, collection)
{
console.log('Collection:');
// ================ THIS WORKS =================
// insert :
// collection.insert({
// id: "1",
// name: "Marciano",
// email: "email@email.nl",
// }, function()
// {
// console.log('inserted!');
// });
// collection.insert({
// id: "2",
// name: "Edward Elric",
// email: "edward_elric@live.nl",
// }, function()
// {
// console.log('inserted!')
// });
// ======= THIS DOESNT WORK ========
// select:
// specify an object with a key for a 'where' clause
collection.find({'id': '1'}, function(error, cursor)
{
//cursor : iterateing over results
cursor(function(error, user)
{
console.log("found:" + user);
})
})
});
这不是迭代从返回的对象的方式。使用或方法来处理结果
collection.find({“id”:1}).toArray(函数(err,数据){
//数据是集合中的对象数组
});
这是因为您将记录插入数据库而不等待回调。如果您想依次执行此操作,我建议您使用和方法瀑布。
但不管怎样,最好使用你现在正在使用的。
写下这样的东西
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/collection');
var user = new User({ name: 'John' });
user.save(getInsertedUsers);
var getInsertedUsers = function(){
User.find({ name: "John" }, echoUsers); //if you want to get just users named john or
User.find({}, echoUsers);
}
var echoUsers = function(users)
{
console.log(users);
}
那collection.findOne({'id':'1'})呢?您是否也验证了回调(包括插入)中没有任何错误?该错误表明
集合
是未定义的
。我发现很难相信insert
在相同的条件下工作。