gpt4 book ai didi

node.js - Node JS-检查mongoDB中是否存在字段

转载 作者:可可西里 更新时间:2023-11-01 09:57:01 25 4
gpt4 key购买 nike

我不确定我是否在正确的轨道上,但这就是我所拥有的......

router.post('/login', function(request, response) {
User.find({ 'username': request.body.email,'email':request.body.pwd }, function(err, user) {
//do not know what to add here

我从两个输入字段获取 POST 数据,然后使用 find 命令检查我的 mongo 数据库中是否已经存在该字段。

User 是我创建的模型架构。看起来是这样……

var Schema = new mongoose.Schema({
email : String,
password : String,
display : String
});
var User = mongoose.model('User', Schema);

我认为我走在正确的轨道上,但我不确定要在 find 命令中添加什么。如果两个字段一起存在,我想做一件事,如果它们不存在我想抛出错误,我该怎么做?

最佳答案

我建议使用 findOne 而不是 find,因为如果存在,它将返回单个文档,否则返回 null

router.post('/login', function(request, response) {
// use `findOne` rather than `find`
User.findOne({
'username': request.body.email,
'email':request.body.pwd }, function(err, user) {
// hanlde err..
if (user) {
// user exists
} else {
// user does not exist
}
})
})

关于node.js - Node JS-检查mongoDB中是否存在字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35833176/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com