简体   繁体   English

Nodejs聚合查找返回空数组

[英]Nodejs aggregate lookup returns empty array

I have user model我有用户 model

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);

and documents model和文件 model

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);

I want to join collections so that for every user exists the user_docs field with docs data as in code below.我想加入 collections 以便每个用户都存在带有文档数据的 user_docs 字段,如下面的代码所示。 I'm trying to do that with joining _id with creator as it is defined when creating a document我正在尝试通过将 _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!"
      });
    });
};

I'm recieveing empty user_docs array.我收到空的 user_docs 数组。 Thank you for your help谢谢您的帮助

If someone has the same problem.如果有人有同样的问题。 I solved it by changing我通过改变解决了

from: "Docs"

to

from: Docs.collection.name

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM