英文:
MongoDB: I'm using find() to get a specific value but instead getting multiple results
问题
工作中在制作一个Facebook克隆版,正在设置上传用户个人资料图片功能。我有一个User
模式,其中包括一个profilePicture
对象。用户访问页面,上传一张图片,然后该图片的URL被添加到他们的profilePicture
值中。
User
模式
const userSchema = new mongoose.Schema({
username: String,
profilePicture: String,
});
以下是数据库中用户的示例。
_id: 642716b83w306234dx8d6cab
username: "Dagger"
profilePicture: "public\images\uploads\a7c770ff72d830a4fb0c8f6963ab9aa8"
这是获取我的profilePicture
的GET请求。我正在使用User.find()
来查找profilePicture
。
router.get("/:user/profile-picture", (req, res) => {
User.find({}, "profilePicture").exec(function (err, profilePicture) {
if (err) {
return next(err);
}
res.render("picture", { user, id, picture, profilePicture });
});
});
但当我将img
代码添加到ejs页面时,什么都不显示。
<div class="avatar">
<img src="<%= profilePicture %>.jpg" alt="logo" />
</div>
当我检查元素时,我注意到<%= profilePicture %>
的值是数据库中每个用户的列表。如何将其缩小,以便仅获取设置为"public\images\uploads\a7c770ff72d830a4fb0c8f6963ab9aa8"
的值?
英文:
Working on a Facebook clone and I'm setting up uploading a profile picture. I have a User
schema with a profilePicture
object. The user visits the page, uploads a picture and that image URL gets added to their profilePicture
value.
User
schema
const userSchema = new mongoose.Schema({
username: String,
profilePicture: String,
});
Here's an example of what a User looks like in the DB.
_id: 642716b83w306234dx8d6cab
username: "Dagger"
profilePicture: "public\images\uploads\a7c770ff72d830a4fb0c8f6963ab9aa8"
And here is the GET request for my profilePicture. What I'm doing is using User.find()
to find the profilePicture
router.get("/:user/profile-picture", (req, res) => {
User.find({}, "profilePicture").exec(function (err, profilePicture) {
if (err) {
return next(err);
}
res.render("picture", { user, id, picture, profilePicture });
});
});
but when I add the img
code to the ejs page nothing shows up.
<div class="avatar">
<img src="<%= profilePicture %>.jpg" alt="logo" />
</div>
When I inspect the element I notice the value of <%= profilePicture %>
is a list of every User in my database. How can I narrow it down so I only get the value set to "public\images\uploads\a7c770ff72d830a4fb0c8f6963ab9aa8"
?
答案1
得分: 1
你会想要使用 findOne()
并指定要搜索的参数。
例如:
User.findOne({ username: 'Dagger' }, "profilePicture").exec(...)
因为你想要它是动态的,所以你需要用一个变量来替换我这里硬编码的 'Dagger'
值,这样你就可以确定要提取哪个用户的照片。
英文:
You would want to use findOne()
and specify the parameter you want to search by.
For Example:
User.findOne({ username: 'Dagger'}, "profilePicture").exec(...)
Being that you want it dynamic, you'd need to replace the hardcoded 'Dagger'
value I use here with a variable so you can identify which user's photo to pull.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论