Mongoose - 将集合填充到一个集合

时间:2018-04-22 09:59:25

标签: mongodb mongoose mongoose-schema mongoose-populate

我在MongoDB中有2个名为“accounts”和“website”的集合。所以我想通过引用将一系列网站连接到一个帐户,我想在查询这些网站所连接的帐户时返回这些网站。

帐户架构

const mongoose = require("mongoose");

const accountSchema = mongoose.Schema({
    _id: mongoose.Schema.Types.ObjectId,
    email: {
        type: String,
        required: true,
        unique: true,
        match: /[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/
    },
    password: {type: String, required: true},
    websites: [{
        type: mongoose.Schema.Types.ObjectId,
        ref: 'Website'
    }]
})

module.exports = mongoose.model("Account", accountSchema);

网站架构

const mongoose = require("mongoose");

const websiteSchema = mongoose.Schema({
    _id: mongoose.Schema.Types.ObjectId,
    url: {
        type: String,
        required: true,
        unique: true,
        match: /[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)/
    },
    account: {type: mongoose.Schema.Types.ObjectId, ref: 'Account'}
})

module.exports = mongoose.model("Website", websiteSchema);

创建网站端点

  router.post("/create", (req, res, next) => {
  const accountID = req.body.accountID
  Account.findById(accountID)
    .then(account => {
      if(!account) {
        return res.status(404).json({
          message: "Account not found"
        });
      }
      const website = new Website({
        _id: mongoose.Types.ObjectId(),
        url: req.body.url,
        account: accountID
      })
      return website.save()
    })
    .then(result => {
      console.log(result);
      res.status(201).json({
        message: "Website stored",
        createdWebsite: {
          id: result._id,
          account: result.account
        },
        request: {
          type: "POST"
        }
      })
    })
    .catch(err => {
      res.status(500).json({
        error: err
      })
    })
})

但是当我在下面提交此请求时,与帐户相关的网站会返回空白。你能帮帮我吗?

查询端点

router.get("/list", (req, res, next) => {

Account.find()
    .populate("websites")
    .exec()
    .then(accounts => {
      res.status(200).json({
        count: accounts.length,
        accounts: accounts.map(account => {
          return {
            id: account._id,
            email: account.email,
            websites: account.websites.map(website => {
              return {
                url: website.url
              }
            })
          }
        })
      })
    })
    .catch(err => {
      res.status(500).json({
        error: err
      })
    })
})

1 个答案:

答案 0 :(得分:0)

您已使用字段名Accountwebsites定义了架构,但您填充了字段website。它应该是websites而不是

router.get(“/ list”,(req,res,next)=> {

Account.find()
    .populate("websites")
    .exec()
    .then(accounts => {
      res.status(200).json({
        count: accounts.length,
        accounts: accounts.map(account => {
          return {
            id: account._id,
            email: account.email,
            websites: account.websites.map(website => {
              return {
                url: website.url
              }
            })
          }
        })
      })
    })
    .catch(err => {
      res.status(500).json({
        error: err
      })
    })
})