【问题标题】:Mongoose populate does not populate arrayMongoose 填充不填充数组
【发布时间】:2019-01-31 10:12:56
【问题描述】:

我已经为mongoose.model.populate 函数苦苦挣扎了好几个小时。我什至尝试过直接复制和粘贴几个解决方案,但没有运气。

我有一个用户模型,它应该包含他/她创建的“困境”数组,但我无法填充它。

这里是模型以及populate()的实现。

User.js

const mongoose = require("mongoose");
const Schema = mongoose.Schema;

// Create Schema
const UserSchema = new Schema({
  username: {
    type: String,
    required: true
  },
  email: {
    type: String,
    required: true
  },
  password: {
    type: String,
    required: true
  },
  date: {
    type: Date,
    default: Date.now
  },
  dilemmas: [
    {
      type: Schema.Types.ObjectId,
      ref: "Dilemma"
    }
  ]
});

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

Dilemma.js

const mongoose = require("mongoose");
const slug = require("mongoose-slug-generator");
const Schema = mongoose.Schema;
mongoose.plugin(slug);

// Create Schema
const DilemmaSchema = new Schema({
  creator: {
    type: mongoose.Schema.Types.ObjectId,
    ref: "User"
  },
  title: {
    type: String
  },
  slug: {
    type: String,
    slug: "title"
  },
  red: {
    type: String,
    required: true
  },
  blue: {
    type: String,
    required: true
  },
  red_votes: {
    type: Number,
    default: 0,
    required: true
  },
  blue_votes: {
    type: Number,
    default: 0,
    required: true
  },
  likes: [
    {
      user: {
        type: Schema.Types.ObjectId,
        ref: "User"
      }
    }
  ],
  comments: [
    {
      user: {
        type: Schema.Types.ObjectId,
        ref: "User"
      },
      text: {
        type: String,
        required: true
      },
      author: {
        type: String
      },
      avatar: {
        type: String
      },
      date: {
        type: Date,
        default: Date.now
      }
    }
  ],
  date: {
    type: Date,
    default: Date.now
  }
});

module.exports = Dilemma = mongoose.model("Dilemma", DilemmaSchema, "dilemmas");

Routes.js

// @route   GET api/users/profile
// @desc    Gets logged in user's profile
// @access  Private
router.get(
  "/profile",
  passport.authenticate("jwt", { session: false }),
  (req, res) => {
    User.find({ username: req.user.username })
      .populate("dilemmas")
      .then(user => {
        if (!user) {
          errors.nouser = "There is no user";
          return res.status(404).json(errors);
        }
        res.json(user);
      })
      .catch(err => res.status(400).json(err));
  }
);

JSON 响应

[
    {
        "_id": "5b807beef770e7c7e6bf7ce0",
        "dilemmas": [],
        "username": "Jonas",
        "email": "Mohrdevelopment@gmail.com",
        "password": "$2a$10$QaqljS9x08YQ9N9EuCBTpO114ZJUFuVxAV80xMzImNi8eW2frPg0C",
        "date": "2018-08-24T21:43:10.411Z",
        "__v": 0
    }
]

JSON 困境响应

[
    {
        "red_votes": 0,
        "blue_votes": 0,
        "_id": "5b80975f6e47fecba621f295",
        "user": "5b807beef770e7c7e6bf7ce0",
        "title": "Am i the real author asdsdasd?",
        "red": "This is the red dilemma",
        "blue": "This is the blue dilemma",
        "likes": [],
        "comments": [],
        "date": "2018-08-24T23:40:15.381Z",
        "slug": "am-i-the-real-author-asdsdasd",
        "__v": 0
    },
    {
        "red_votes": 0,
        "blue_votes": 0,
        "_id": "5b808e789bc36bcae8c6c3ad",
        "creator": "5b807beef770e7c7e6bf7ce0",
        "title": "Am i the real author?",
        "red": "This is the red dilemma",
        "blue": "This is the blue dilemma",
        "likes": [],
        "comments": [],
        "date": "2018-08-24T23:02:16.565Z",
        "slug": "am-i-the-real-author",
        "__v": 0
    }
]

JSON 用户响应

{
    "_id": {
        "$oid": "5b807beef770e7c7e6bf7ce0"
    },
    "dilemmas": [],
    "username": "Jonas",
    "email": "Mohrdevelopment@gmail.com",
    "password": "$2a$10$QaqljS9x08YQ9N9EuCBTpO114ZJUFuVxAV80xMzImNi8eW2frPg0C",
    "date": {
        "$date": "2018-08-24T21:43:10.411Z"
    },
    "__v": 0
}

【问题讨论】:

  • 您能否发布这两个文档的样本集合
  • 填充({path:"path",model:"model"})
  • @AnthonyWinzlet,我已经更新了收藏。
  • 您可以尝试在您的视图中呈现困境吗?我相信 populate() 存在一个已知问题,即数据不会显示在 JSON 中,尽管您可以在视图中显示它。
  • @Michael,我想我可以试试。虽然我还没有创建视图,但我会在完成后通知您。

标签: javascript mongodb mongoose nosql mongoose-populate


【解决方案1】:

我自己也遇到了类似的问题。填充一个引用有效,但填充一个引用数组没有。通过在填充调用中明确指定模型名称,我能够使数组填充工作,例如:

User.find({ ... }).populate({
  path: 'dilemmas',
  model: 'Dilemma',
});

当引用模型的名称已在架构中指定时,我不知道为什么这会有所不同。

【讨论】:

  • 成功了 :).Super
【解决方案2】:

你试过了吗?

User.find({ username: req.user.username })
  .populate("dilemmas")
  .exec() // <-- add exec() to perform the search
  .then(user => {
    ...
  })

【讨论】:

  • 你确定你的用户Jonas在数据库中遇到了难题吗?
  • 是的,我实际上发布了显示它的 json 响应,可能已被删除。
  • 我问这个是因为响应 JSON 有一个空的 dilemmas 数组,其中没有任何 objectId
  • 是的,这就是整个问题。帖子中的 JSON 是来自配置文件路由的响应,它应该包含用户创建的所有 dilemmas。我已确认数据库中存在dilemmas,其作者ID 与user 相同
【解决方案3】:

你检查过这里的文档吗?

https://mongoosejs.com/docs/populate.html#refs-to-children

它显示了类似的设置(包括作者和故事。)它提到“推送”故事以便能够使用 find / populate 组合。

【讨论】:

  • 是的,我之前读过它并试图复制他们为我的项目展示的内容。但似乎没有任何效果......
猜你喜欢
  • 2019-07-28
  • 2020-06-07
  • 2014-12-05
  • 1970-01-01
  • 1970-01-01
  • 2020-05-18
  • 2012-01-22
  • 2015-03-26
  • 2019-02-13
相关资源
最近更新 更多