【发布时间】:2018-09-25 04:15:28
【问题描述】:
给出的是:
var item = {
email: req.body.email,
//pw: req.body.pw,
pw: encpassword,
timestamp: Date.now()
};
var mailAddress = item.email;
var resultArrayEmail = [];
MongoClient.connect(url, { useNewUrlParser: true }, function(err, client) {
// assert.equal(null, err);
const db = client.db(dbName);
//####### Proof of exist
var cursor = db.collection('userdata').find();
var cursorCheck = db.collection('userdata').findOne({"email": mailAddress});
if (cursorCheck.length > 0){
console.log('Item exists');
}else{
db.collection('userdata').insertOne(item, function(err, result) {
assert.equal(null, err);
client.close();
});
// cursor.forEach(el => console.log(el.email)); => Returns all emailadresses within a collection
console.log(item);
console.log('inserted!');
}
res.redirect('/register');
});
Using indexOf to filter an array 我已经这样尝试过了,它工作正常,但似乎 mongoDB-collection 不是一个对象数组...... -> 所以它不适用于这个解决方案。
如果电子邮件地址已经存在,如何检查“字段”电子邮件?
【问题讨论】:
-
你想做什么,怎么没用?
-
findOne将返回对象而不是数组,因此cursorCheck.length > 0将不起作用。 -
使用
count()代替这里MongoDB count collection Node.js