乐闻世界logo
搜索文章和话题

Mongoose 如何使用 findOne?

5 个月前提问
3 个月前修改
浏览次数71

5个答案

1
2
3
4
5

在Mongoose中,findOne 方法用于在MongoDB数据库中查询并返回匹配特定查询条件的单个文档。这个方法接受一个查询对象作为参数,该对象指定了我们希望查找的文档的条件。返回的是一个满足条件的文档,如果没有找到,则返回 null

以下是一个使用 findOne 方法的例子:

假设我们有一个名为 User 的模型,它代表一个用户集合。我们想查询一个用户名为 "johndoe" 的用户:

javascript
const mongoose = require('mongoose'); const User = mongoose.model('User', new mongoose.Schema({ username: String, email: String, password: String })); async function findUserByUsername(username) { try { // 使用 findOne 方法查找一个用户名为 'johndoe' 的用户 const user = await User.findOne({ username: username }); if (user) { // 用户被找到 console.log(`User found: ${user}`); return user; } else { // 用户未找到 console.log('User not found.'); return null; } } catch (error) { // 错误处理 console.error('An error occurred:', error); } } // 调用函数并传入用户名 'johndoe' findUserByUsername('johndoe');

在上面的代码示例中,我们首先引入了 mongoose 并定义了一个 User 模型,该模型具有用户名(username)、电子邮件(email)和密码(password)属性。

我们定义了一个异步函数 findUserByUsername,它接受一个用户名作为参数,然后使用 findOne 方法根据提供的用户名查询用户。查询参数是一个对象,即 { username: username },在这里我们希望 username 字段与传入的 username 参数相匹配。

该函数使用 await 关键字等待 findOne 的执行结果,这意味着在返回结果之前,JavaScript 的事件循环可以继续处理其他事情。如果查询成功,并且找到了对应的用户,它将打印出找到的用户并将其返回。如果没有找到用户,则输出 "User not found."。如果查询过程中发生错误,则会捕获该错误,并在控制台中打印出来。

2024年6月29日 12:07 回复

Found the problem, need to use function(err,obj) instead:

shell
Auth.findOne({nick: 'noname'}, function(err,obj) { console.log(obj); });
2024年6月29日 12:07 回复

Mongoose basically wraps mongodb's api to give you a pseudo relational db api so queries are not going to be exactly like mongodb queries. Mongoose findOne query returns a query object, not a document. You can either use a callback as the solution suggests or as of v4+ findOne returns a thenable so you can use .then or await/async to retrieve the document.

shell
// thenables Auth.findOne({nick: 'noname'}).then(err, result) {console.log(result)}; Auth.findOne({nick: 'noname'}).then(function (doc) {console.log(doc)}); // To use a full fledge promise you will need to use .exec() var auth = Auth.findOne({nick: 'noname'}).exec(); auth.then(function (doc) {console.log(doc)}); // async/await async function async auth() { const doc = await Auth.findOne({nick: 'noname'}).exec(); return doc; } auth();

See the docs if you would like to use a third party promise library.

2024年6月29日 12:07 回复

In my case same error is there , I am using Asyanc / Await functions , for this needs to add AWAIT for findOne

shell
Ex:const foundUser = User.findOne ({ "email" : req.body.email });

above , foundUser always contains Object value in both cases either user found or not because it's returning values before finishing findOne .

shell
const foundUser = await User.findOne ({ "email" : req.body.email });

above , foundUser returns null if user is not there in collection with provided condition . If user found returns user document.

2024年6月29日 12:07 回复

You might want to consider using console.log with the built-in "arguments" object:

shell
console.log(arguments); // would have shown you [0] null, [1] yourResult

This will always output all of your arguments, no matter how many arguments you have.

2024年6月29日 12:07 回复

你的答案