MongoDB NodeJS返回子文档

编程入门 行业动态 更新时间:2024-10-17 11:31:08
本文介绍了MongoDB NodeJS返回子文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在尝试返回与查询字段匹配的子文档.我只想返回与用户匹配的PIN,该PIN保留在帐户集中.这是我到目前为止所掌握的.

I'm trying to return a subdocument that matches the query fields. I just want to return the PIN that matches the user, which is held in the account collection. This is what I've got so far.

router.post('/SelectUser', async(req, res) =>{ try{ const acc = await Account.findOne({"Email": req.body.Email}); if(!acc) throw Error('Email not found'); var user = await Account.findOne({"Users.Username":req.body.User.Username},{Users:{PIN:1}}); }

这将输出与帐户关联的所有PIN,这不是我想要的.这是我正在使用的模式和模型:

This outputs all the PINs associated with an account, which isn't what I want. Here are the Schemas and Models that I'm using:

帐户:

const User = require('../Models/UserData'); const AccountSchema = new Schema({ // Email linked to this account Email:{ type:String, unique:true, required:true, index:true }, // Password for the account Password:{ type : String, required : true }, // Users on this account Users:{ type:[User], required:true } }); module.exports = mongoose.model('Account', AccountSchema);

用户:

const UserSchema = new Schema({ // Name of the user Username:{ type:String, required:true, unique:true }, // PIN for each user PIN:{ type:Number, require:true } }); module.exports = UserSchema;

推荐答案

您尝试做的事情在您的应用中非常简单(例如,在 findOne 之后的JS代码),但是如果您确实如此想要在mongodb中做到这一点,那么您将需要使用聚合.将您的代码更改为:

What you're trying to do would be pretty trivial in your app (i.e JS code after findOne), but if you really want to do it in mongodb, then you will need to use aggregation. Change your code to:

const username = req.body.User.Username; const user = await Account.aggregate([ { $match: { "Users.Username": username } }, { "$project": { _id: false, USER: { $filter: { input: "$Users", as: "users", cond: { $eq: [ "$$users.Username", username ] } } } } }, { "$unwind": "$USER" }, { "$project": { USER_PIN: "$USER.PIN" } } ]); if(user.length){ console.log(user[0].USER_PIN) }else{ console.log('Username not found') }

以下是实际的汇总查询,供您使用: mongoplayground/p/o-xTTa8R42w

Here is the actual aggregation query for you to play around with: mongoplayground/p/o-xTTa8R42w

更多推荐

MongoDB NodeJS返回子文档

本文发布于:2023-11-22 13:39:55,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1617637.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:文档   MongoDB   NodeJS

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!