猫鼬填充不填充数组

时间:2018-08-24 23:22:41

标签: javascript mongodb mongoose nosql mongoose-populate

我已经在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
}

3 个答案:

答案 0 :(得分:0)

您尝试过吗?

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

答案 1 :(得分:0)

您是否在此处查看了文档?

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

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

答案 2 :(得分:0)

我自己也遇到了类似的问题。填充参考有效,但填充参考数组无效。我可以通过在填充调用中明确指定模型名称来使数组填充正常工作,例如:

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

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

相关问题