繁体   English   中英

节点 js/猫鼬 .find()

[英]Node js / Mongoose .find()

我在 node js 服务器上的 mongoose 中使用 .find() 函数时遇到问题我一直在尝试使用它,但我无法从我的数据库中获取关键信息。

user.find({key: 1} , function(err, data){
  if(err){
    console.log(err);
  };
  console.log("should be the key VVV");
  console.log(data.key);
});

我主要只是在思考这个函数如何获取查询并从数据库返回响应时遇到问题。 如果有人可以分解它,我将非常感谢猫鼬文档并没有太大帮助。

如果有帮助,这也是我的用户架构

var userSchema = new mongoose.Schema({
  username: {type: String, unique: true},
  password: {type: String},
  key: {type: String},
  keySecret: {type: String}
}, {collection: 'user'});


var User = mongoose.model('user',userSchema);

module.exports = User;

如果你想象你的数据库是这样的:

[
    {
        "name": "Jess",
        "location": "Auckland"
    },
    {
        "name": "Dave",
        "location": "Sydney"
    },
    {
        "name": "Pete",
        "location": "Brisbane"
    },
    {
        "name": "Justin",
        "location": "Auckland"
    },
]

执行以下查询;

myDB.find({location: 'Brisbane'})

将返回:

[
    {
        "name": "Pete",
        "location": "Brisbane"
    }
]

myDB.find({location: 'Auckland'})会给你

[
    {
        "name": "Jess",
        "location": "Auckland"
    },
    {
        "name": "Justin",
        "location": "Auckland"
    },
]

如您所见,您正在通过数组find与您要查找的键匹配的键,并以数组的形式返回与该键搜索匹配的所有文档。

Mongoose 接口以回调的形式将这些数据提供给您,您只需要在它返回的数组中查找项目即可

user.find({location: "Auckland"}, function(err, data){
    if(err){
        console.log(err);
        return
    }

    if(data.length == 0) {
        console.log("No record found")
        return
    }

    console.log(data[0].name);
})

也许你应该使用

Model.findOne({key: '1'}, function(err, data) {
  console.log(data.key);
});

find()会得到一个 doc 数组,而findOne()只能得到一个 doc。

您的字段keyString类型,因此您的查询 obj 应该是{key: '1'} ,而不是{key: 1}

仔细阅读猫鼬文档可能会对您有所帮助。

嗨,我的朋友,我使用这种方法从数据库中检索数据,希望对您有所帮助

user.find({key: 1})
    .then((userOne)=>{
//if is an API
        res.status(200).json({data : userOne});
//OR
// if you had a view named profile.ejs for example
res.render('/profile',{data : userOne, title : 'User profile' }); 
        console.log(userOne); // just for check in console
    })
    .catch((error)=>{
//if an api
res.status(400).json({messageError : error});
// OR
if not an api
res.render('/profile',{data : 'No data of this profile',errorToDisplay : error})
});
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM