Node js / Mongoose .find()

6

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

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

我主要是不太理解这个函数如何将查询结果返回到你的数据库。如果有人能将其简单解释一下,我会非常感激。mongoose文档并没有提供太多帮助。

如果需要,以下是我的用户模式

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;
3个回答

13

如果你想象一下你的数据库长这样:

[
    {
        "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"
    },
]

正如您所看到的,您正在查找与您要查找的键匹配并以数组形式返回符合该键搜索的所有文档的机制。

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);
})

我认为你给出了最好的答案。我本来想插话,但是你在这里创造了很多价值。好答案。 - Joseph Chambers
谢谢,.find()的替代方法是.findOne() - .find()返回一个数组,而.findOne()返回它找到的第一条记录(对象),忽略其余记录。这在查找具有唯一字段的文档时非常有用 - 比如按电子邮件或ID查找。 - David Alsh
1
@darshanan,您是指如何在文档的嵌套键中搜索值吗?如果是这样,那么可以使用db.collections.find({"keyOne.keyTwo":"search"}) - David Alsh
@DavidAlsh 请查看上面的评论。 - darshan a n

4
也许你应该使用:


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

find()会返回文档数组,而findOne()则只返回一个文档。

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

仔细阅读mongoose文档可能会对你有帮助。


我尝试这样做只是为了测试,唯一的问题是我不知道如何在只使用“查找一个键”时将数据库指向正确的条目。有多个用户帐户和密钥的实例。 - Echo

0

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

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})
    });
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接