首页 > 解决方案 > Mongoose 在嵌套数组上运行 Get

问题描述

所以目前我的设置显示了用户的所有结果,这很好,但我只想获得用户持有的名为访问的数组。

到目前为止,这就是我的设置方式:

getClicks() {
    this.http
      .get<{ message: string; users: any }>(
        BACKEND_URL_Analytics + '/user-clicks'
      )
      .pipe(
        map(data => {
          return data.users.map(user => {
            console.log(user);
            return {
              _id: user._id,
          *** visits: [user.visitCount] ****
            };
          });
        })
      )
      .subscribe(
        result => {
          this.userAnalytics = result;
          this.userAnalyticsUpdate.next([...this.userAnalytics]);
        },
        error => {
          console.log(error);
        }
      );
 }

这是我的数据库结构:

const mongoose = require('mongoose');
const uniqueVal = require('mongoose-unique-validator');
const Schema = mongoose.Schema;

const visitsSchema = new Schema ({
  postId: {
    type: String
  },
  visitCount: {
    type: Number,
    default: 1
  }
})

const userSchema = mongoose.Schema({
  email: {
    type: String,
    required: true,
    unique: true
  },
  password: {
    type: String,
    required: true
  },
  role: {
    type: String,
    required: true
  },
  answers: {
    type: String
  },
  visits: [visitsSchema]
});

userSchema.plugin(uniqueVal);

module.exports = mongoose.model('User', userSchema);

我的目标是获取由 mongoose 自动创建的用户 ID,作为 _ID,这很容易做到。但后来我需要访问visits: [visitsSchema].

这是 console.log 结果来自console.log(user);

{_id: "5b3f839e6633e59b673b4a4e", email: "admin@hotmail.com", password: "$2b$10$IJ71o/SSfRDoQY4r./gKaetstvka8fFhh4tk35BUD4ReXaKhw1OrC", role: "admin", visits: Array(2), …}
email:"admin@hotmail.com"
password:"$2b$10$IJ71o/SSfRDoQY4r./gKaetstvka8fFhh4tk35BUD4ReXaKhw1OrC"
role:"admin"
visits:Array(2)
0:{visitCount: 3, _id: "5b7c32015f015d5108002e88", postId: "5b5dbba4c67aad56df79f341"}
1:{visitCount: 1, _id: "5b7c32f72f457a517aaef23b", postId: "5b688fb0e90f608916e7548b"}

console.log 中显示的访问数组包含我需要恢复并发送到前端的 和visitCountpostID关于如何修复地图或返回值以获得正确信息的任何建议。如果获取 ID 太难,那么我会接受只获取visitCountand postID,所以我可以将它添加到表格中并显示它,谢谢!

{
    "message": "Activities were fetched succesfully!",
    "users": [
        {
            "visits": [],
            "_id": "5b3f84246633e59b673b4a50",
            "email": "teacher@hotmail.com",
            "password": "$2b$10$AZad.DdvPYHS4ttkLkQMyeA5wwe49JoSuJ4DvTO8xdp13gIlmF2Xy",
            "role": "teacher",
            "__v": 0
        },
        {
            "_id": "5b3f839e6633e59b673b4a4e",
            "email": "admin@hotmail.com",
            "password": "$2b$10$IJ71o/SSfRDoQY4r./gKaetstvka8fFhh4tk35BUD4ReXaKhw1OrC",
            "role": "admin",
            "visits": [
                {
                    "visitCount": 3,
                    "_id": "5b7c32015f015d5108002e88",
                    "postId": "5b5dbba4c67aad56df79f341"
                },
                {
                    "visitCount": 1,
                    "_id": "5b7c32f72f457a517aaef23b",
                    "postId": "5b688fb0e90f608916e7548b"
                }
            ],
            "__v": 0
       },

Ontop 是我来自后端的邮递员请求,也许这有帮助?谢谢

标签: javascriptnode.jsmongoose

解决方案


我不太明白你的问题。但是,如果您想要获取所有用户的数据,则需要populate()。对于您的情况,您应该这样做:

const visitsSchema = new Schema ({
       postId: {
           type: mongoose.Schema.Types.ObjectId, 
           ref: 'Post', // Reference to your Post model
      },
      visitCount: {
          type: Number,
          default: 1
      }
})

const userSchema = mongoose.Schema({
         email: {
             type: String,
             required: true,
             unique: true
         },
         password: {
             type: String,
             required: true
         },
         role: {
             type: String,
             required: true
         },
         answers: {
             type: String
         },
         visits: [{
             type: mongoose.Schema.Types.ObjectId, 
             ref: 'Visits', // Reference to your Visit model
         }]
});

然后我想你的模型是这样的:

userSchema.plugin(uniqueVal);

module.exports = mongoose.model('User', userSchema);
module.exports = mongoose.model('Post', postSchema);  // <- I suppose you have this
module.exports = mongoose.model('Visits', visitsSchema); // <- I suppose you have this

现在您可以获取有关您的用户的所有信息,例如如下所示:

User.findOne({email: 'admin@hotmail.com'})
    .populate({
        path: 'visits',
        populate: { path: 'postId' }
    });

您可以在多个级别使用 populate()。


推荐阅读