使用猫鼬的一对多关系MongoDb

时间:2018-02-06 19:56:01

标签: node.js mongodb mongoose

我正在创建用户和地址之间的关系。用户可以拥有多个地址。这是我的架构:

userSchema.js

const mongoose = require('mongoose')
const Schema = mongoose.Schema
const Address = require('./addressSchema')


let userSchema = mongoose.Schema({
  name :String,
  age : Number,
  cohort :String,
  addresses : [{type : Schema.Types.ObjectId, ref : 'Address'}]
})


let User = mongoose.model('User',userSchema)

module.exports = User

addressSchema.js

const mongoose = require('mongoose')

let addressSchema = mongoose.Schema({
  city : String,
  state :String
})

let Address = mongoose.model('Address',addressSchema)
module.exports = Address

添加新用户和地址(app.js)

let user = new User({name : 'Mary', age : 36, cohort : 2019})
let address = new Address({ city : 'Houston', state : 'TX'})

user.addresses.push(address)


user.save(function(error,newUser){
  console.log(newUser)
})

获取用户及其地址 //获取所有用户

User.find(function(error,users){

  users.forEach((user) => {
    console.log('addresses')
    user.addresses.forEach((address) => {
      console.log(address.city) // prints undefined
    }) 
  })

})

任何想法我做错了什么?

1 个答案:

答案 0 :(得分:0)

这取决于您要完成的任务:将地址作为嵌入文档存储在用户中,用于存储对用户地址文档的引用。上面的示例代码混合了两种方法,正如您所注意到的那样,它们不起作用。

嵌入式:

结合模式:

const mongoose = require('mongoose')
const Schema = mongoose.Schema
const addressSchema = Schema({
    city : String,
    state :String
})'

const userSchema = Schema({
  name :String,
  age : Number,
  cohort :String,
  addresses : [addressSchema]
});

const User = mongoose.model('User',userSchema);

其余代码可以保持不变。

参考文献:

现有的架构和模型声明保持不变。

然后,当存储数据时,还需要存储地址:

const user = new User({name : 'Mary', age : 36, cohort : 2019})
const address = new Address({ city : 'Houston', state : 'TX'})

user.addresses.push(address)

Promise.all([
  user.save(),
  address.save()
]).then(([newUser, newAddress]) => {
  console.log({newUser, newAddress});
});

最后在获取文档时,如果要包含该地址,则需要填充该文档:

User.find().populate('addresses').exec().then((users) => {
  users.forEach((user) => {
    user.addresses.forEach((address) => {
      console.log({user, address});
    });
  });
});