用javascript,游标方法查询mongodb

时间:2012-07-08 12:22:16

标签: node.js mongodb mongodb-query

我只是创建一个简单的用户登录,使用MongoDB,Backbone和Node with Express。

我一直在查询数据库中的用户凭据,并可靠地确定它们是否存在。

我在这里尝试两件事:

// When user posts to the url
app.post('/save/user', function (req, res) {

  // create user object and store email from form
  var user = {
    email : req.body.email
  };

  // in my collection users
  db.collection('users', function (err, collection) {

    // create a variable existence with the value, in lamens terms 'yes it does' or 'no it doesnt'
    var existence = findOne(collection, {
      $query : {email : user.email}
    });

  });
};

// findOne function passing the collection and the query object
function findOne(coll, query) {
  var cursor = coll.find(query).limit(1);
  return cursor.hasNext() ? cursor.next() : null;
}

所以这是我一直在尝试的第一种方式。事情是,我不明白为什么游标没有'next(),hasNext(),findOne(),forEach()'和javascript环境的其他方法,但只有mongo shell。

我的问题是,如何在我的Node.js应用程序中访问这些方法?

我试过的第二种方式:

//当用户发布到网址时     app.post('/ save / user',function(req,res){

  // create user object and store email from form
  var user = {
    email : req.body.email
  };

  // in my collection users
  db.collection('users', function (err, collection) {

    // Have a look for the email entered
    var query = collection.find({
      $query : {email : user.email}
    }).limit(1);

    // If it's true, then send response
    query.each( function (err, item) {

      // If the item does exists, then send back message and don't insert. Otherwise, insert.
      if(item !== null) {
        console.log('Item does not equal null : ', item);
        res.send('The email : ' + item.email + ' already exists');
      } else {
        console.log('Item does equal null : ', item);
        collection.insert(user);
        res.send('New user with email : ' + user.email + ' was saved');
      }

    });

  });
};

这个问题是,它总是会在某个时刻返回null,所以我要警告用户'它已经存在',然后下一次将为null,这样就可以保存电子邮件。

我认为我错过了这一点,所以正确方向上的一点很好。

非常感谢提前!


我已经研究过一个解决方案,但仍然必须忽略这一点。

我正在进行插入操作,使用safe:true传递我的用户对象,但是虽然可以输入多个用户对象,但它仍然只查找相同的ID; s。我尝试使用新的ObjectID()创建一个id,但我仍然不明白用户是否输入了他们的电子邮件地址,然后尝试创建一个具有相同电子邮件的新用户,它会为该条目创建一个新ID。

通过执行findOne,我可以看到它是否容易存在,我看不出如何使用insert。

app.post('/register/user', function (req, res) {

// Store user details in object
var user = {
  username : req.body.user,
  email : req.body.email,
  password : req.body.password
};

db.collection('users', function (err, collection) {

  collection.insert(user, {safe : true}, function (err, doc) {

    console.log('what is doc : ', doc);
    if(!err) {
      res.writeHead(200, {
        "Content-Type" : "text/plain",
        "Message" : "New user added",
        "Access-Control-Allow-Origin" : "*"
      });
    } else {
      console.log('Error is : ', err);
      res.writeHead(200, {
        "Content-Type" : "text/plain",
        "Message" : "User already exists",
        "Access-Control-Allow-Origin" : "*"
      });
    }

    res.end();

  });

});

});

1 个答案:

答案 0 :(得分:2)

如果您使用Native Node.JS MongoDB driver,则有collection.findOne()方法,而cursors确实有nextObject()each()方法等同于shell方法{ {1}}和hasNext()。 mongo shell等价物的实现/命名在驱动程序之间可能略有不同,但您应该能够将mongo shell示例转换为Node.JS。

至于保存新用户...而不是在插入之前查询用户,最好在forEach()字段和insert into the collection上添加唯一索引{{1} }。如果插入因电子邮件重复而失败,则可以处理email结果。如果在插入之前执行查询,则存在潜在的竞争条件,当您检查电子邮件时,该电子邮件可能不存在,但在您执行插入时确实存在。

相关问题