首页 > 解决方案 > Nodejs聚合查找返回空数组

问题描述

我有用户模型

const mongoose = require("mongoose");
const uniqueValidator = require("mongoose-unique-validator");

const userSchema = mongoose.Schema({
  email: { type: String, required: true, unique: true },
  password: { type: String, required: true },
  isEmailVerified: { type: Boolean },
  registrationStep: { type: Number, enum: [0,1,2,3]},
  regDate: { type: Date },
  companyName: { type: String },
  oib: { type: String },
  telephone: { type: String },
  address: { type: String },
  city: { type: String },
  countryCode: { type: String },
  postalCode: { type: String },
  userType: { type: String, enum:['firms','drivers','both']},
  approved: { type: Boolean },
  isAdmin: { type: Boolean }
});

userSchema.plugin(uniqueValidator);

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

和文件模型

const mongoose = require("mongoose");

const docsSchema = mongoose.Schema({
  docsPath: { type: String, required: true },
  creator: { type: mongoose.Schema.Types.ObjectId, ref: "User", required: true },
  docType: { type: String, enum:['isr','lmp','pocmr'], required: true }
});

module.exports = mongoose.model("Docs", docsSchema);

我想加入集合,以便每个用户都存在带有文档数据的 user_docs 字段,如下面的代码所示。我正在尝试通过将 _id 与创建者连接来做到这一点,因为它是在创建文档时定义的

exports.getUsersAndDocs = (req, res, next) => {
  const query = User.aggregate([
    {
    $lookup: {
      from: "Docs",
      localField: "_id",
      foreignField: "creator",
      as: "user_docs"
    }
  }]);
  query
    .then(fetchedUsers => {
      res.status(200).json({
        message: "Users fetched successfully!",
        users: fetchedUsers,
      });
    })
    .catch(error => {
      res.status(500).json({
        message: "Fetching users failed!"
      });
    });
};

我收到空的 user_docs 数组。谢谢您的帮助

标签: javascriptnode.jsmongodb

解决方案


如果有人有同样的问题。我通过改变解决了

from: "Docs"

from: Docs.collection.name

推荐阅读