【问题标题】:Use populate() for two different schemas in MongoDB对 MongoDB 中的两个不同模式使用 populate()
【发布时间】:2015-07-06 18:43:55
【问题描述】:

我有两个 MongoDB 集合 - cmets

var mongoose = require('mongoose');

var CommentSchema = new mongoose.Schema({
  body: String,
  author: String,
  upvotes: {type: Number, default: 0},
  post: { type: mongoose.Schema.Types.ObjectId, ref: 'Profile' }
});

mongoose.model('Comment', CommentSchema);

和用户

var mongoose = require('mongoose');

var UserSchema = new mongoose.Schema({
  userName: String,
  userJobRole: String,
  userEmail: String,
  userPhone: String,
  userTimeZone: String,
  post: { type: mongoose.Schema.Types.ObjectId, ref: 'Profile' }
});

mongoose.model('User', UserSchema);

我想在我的 get 请求中为这些模式中的每一个使用填充。一个用于用户,一个用于这些模型的 cmets。

router.get('/profiles/:profile', function(req, res, next) {
  req.post.populate('users', function(err, post) {
    if(err) { return next(err) }
    res.json(post);
  });
});

我只能弄清楚如何调用一个。

Mongoose 是否允许您从两个模式中进行填充?

【问题讨论】:

    标签: node.js mongodb mongoose


    【解决方案1】:

    为了填充多个路径,您可以将空格分隔的路径名称字符串传递给任何文档的填充方法,如下所示:

    Story
    .find(...)
    .populate('fans _creator') // space delimited path names
    .exec()
    

    这是直接取自 Mongoose 文档http://mongoosejs.com/docs/populate.html

    【讨论】:

    • 谢谢。 router.get('/profiles/:profile', function(req, res, next) { req.post.populate('users cmets', function(err, post) { if(err) { return next(err) } res.json(post); }); });成功了
    猜你喜欢
    • 2018-01-14
    • 2023-04-09
    • 1970-01-01
    • 2014-09-22
    • 1970-01-01
    • 1970-01-01
    • 2015-01-08
    • 1970-01-01
    • 2017-12-12
    相关资源
    最近更新 更多