猫鼬填充的正确方法是什么?

时间:2018-04-12 03:41:25

标签: javascript node.js mongodb express mongoose

你好我是nodejs和mongoose的新手,我需要mongoose populate的帮助,请帮我理解。提前致谢! 这是我的架构

PropertySchema.js

const mongoose = require('mongoose')
const { Schema } = mongoose
require('./MemberSchema')

const propertySchema = mongoose.Schema({
  _id: mongoose.Schema.Types.ObjectId,
  pname: String,
  ptype: String,
  price: Number,
  owner: { type: mongoose.Schema.Types.ObjectId, ref: 'Members' }
})


const Props = mongoose.model('Property', propertySchema)

module.exports = Property

MemberSchema.js

const mongoose = require('mongoose')
const { Schema } = mongoose
require('./PropertySchema')

const memberSchema = mongoose.Schema({
  _id: mongoose.Schema.Types.ObjectId,
  fname: String,
  lname: String,
  dob: Number,
  email: String,
  address: String,
  phone: Number,
  memtype: String,
  username: {type: String, required: true},
  password: {type: String, required:true},
  properties: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Property' }]
})

const Members = mongoose.model('Members', memberSchema)

module.exports = Members

addPropertyRoutes.js

router.post('/add', isAuthenticated, (req, res, next) => {
  const props = new Property({
    _id: new mongoose.Types.ObjectId(),
    pname: req.body.pname,
    ptype: req.body.ptype,
    price: req.body.price,
    owner: new mongoose.Types.ObjectId()
  })
  props.save( (err, props) => {
    if (err) {
      console.log('Unable to register your data: ' + err)
      throw err
    }
    console.log('Property Added Successful!')
    res.redirect('/property/add')
  })
})  

我正在使用mongoose 3.6和expressjs。

当我在添加属性后检查我的Robo 3t时,它会显示如下:检查此屏幕截图:

enter image description here

2 个答案:

答案 0 :(得分:0)

在您的属性架构中,您必须存储ownerId,而不是生成新的ObjectId。 在mongoose中进行Populate的正确方法,你可以找到它here

答案 1 :(得分:0)

我认为解决方案是:

将addPropertyRoutes更改为:)

router.post('/add', isAuthenticated, (req, res, next) => {
      const member = req.user
      Members.findOne({})
      const props = new Property({
        pname: req.body.pname,
        ptype: req.body.ptype,
        price: req.body.price,
        owner: member._id
      })
      props.save( (err, props) => {
        if (err) {
          console.log('Unable to register your data: ' + err)
          throw err
        }
        console.log('Registration Successful!')
        res.redirect('/property/add')
      })
    })

欢迎你来自新手