嵌套的ObjectId填充数组

问题描述

我正在尝试populate中的array of ObjectId mongoose。在该数组内,将再次需要populate

假设我具有User数据模式,如下所示:-

  • models/User.js

    /** Dependencies */
    // Mongoose
    const mongoose = require('mongoose')
    
    /** Data Schema */
    // User Data Schema
    const UserSchema = new mongoose.Schema({
        // User's Name
        name: {
            // User's Firstname
            firstName: { type: String,required: true,min: 4 },// User's Lastname
            lastName: { type: String,min: 4 }
        },// User's Address Array[ID]
        address: [{
            // AddressID
            addressID: { type: mongoose.Schema.Types.ObjectId,ref: "Address" },}]
    })
    
    /** Data Schema Exports */
    module.exports = mongoose.model('User',UserSchema);
    
  • Address模式models/Address.js

    /** Dependencies */
    // Mongoose
    const mongoose = require('mongoose')
    
    /** Data Schema */
    // Address Data Schema
    const AddressSchema = new mongoose.Schema({
        // Address 1
        addressOne: { type: String,required: true },// Address 2
        addressTwo: { type: String },// Postcode
        postcode: { type: String,// City
        city: { type: String,// StateID
        state: { type: mongoose.Schema.Types.ObjectId,ref: "State" },// CountryID
        country: { type: mongoose.Schema.Types.ObjectId,ref: "Country" }
    })
    
    // State Data Schema
    const StateSchema = new mongoose.Schema({
        // Gender's Name
        name: { type: String,required: true }
    })
    
    // Country Data Schema
    const CountrySchema = new mongoose.Schema({
        // Race's Name
        name: { type: String,required: true }
    })
    
    /** Data Schema Export */
    const Address = mongoose.model('Address',AddressSchema)
    const State = mongoose.model('State',StateSchema)
    const Country = mongoose.model('Country',CountrySchema)
    module.exports = {
        Address,State,Country
    }
    

我知道如何populate state countryAddress,如下所示:-

Address.find()
.populate('state')
.populate('country')
.then(async address => {
    // do stuff
})
.catch(err => res.json({ err }))

但是我怎么populate的{​​{1}}数组。我做了如下所示的代码:-

ObjectId

很不幸,User.findById({ _id: userId }) // let's say I've the userId .populate('address') .then(async user => { console.log(await user) }) .catch(err => res.json({ err })) 我是这样的:-

returns

我想要得到的如下所示:-

{
    "_id": "5fabababababababababab1"
    "name": {
        "firstName": "Lalapolalaa","lastName": "Newb"
    },"address": [
        {
            "_id": "5fcdcdcdcdcdcdcdcdc1","addressID": "5fefefefefefefefefef1" // should've populate (but not working)
        }
    ],"__v": 0   
}

如何通过下面的当前代码获取该信息(如上所示):-

{
    "_id": "5fabababababababababab1"
    "name": {
        "firstName": "Lalapolalaa","addressID": { // populate happens here
                "_id": "5fefefefefefefefefef1","addressOne": "Lot 1,Street 12","addressTwo": "SS 21","postcode" : "47500","city": "Subang Jaya","state": { // populate happens here
                    "_id": "5fghghghghghghghghg1","name": "Selangor","__v": 0
                },"country": { // populate happens here
                    "_id": "5ijijijijijijijijij1","name": "Malaysia","__v": 0
                }
                "__v": 0
            }
        }
    ],"__v": 0   
}

解决方法

我可以通过以下更正找到自己的解决方案:-

  • models/User.js中:-
/** Dependencies */
// Mongoose
const mongoose = require('mongoose')

/** Data Schema */
// User Data Schema
const UserSchema = new mongoose.Schema({
    // User's Name
    name: {
        // User's Firstname
        firstName: { type: String,required: true,min: 4 },// User's Lastname
        lastName: { type: String,min: 4 }
    },// User's Address Array[ID]
    address: [{ type: mongoose.Schema.Types.ObjectId,ref: "Address" }] // 1st Correction
})

/** Data Schema Exports */
module.exports = mongoose.model('User',UserSchema);

然后接下来,我可以直接进行如下所示的代码(解决方案):-

User.findById({ _id: userId }) // let's say I've the userId
.populate('address') // assuming this populate of address works
.then(async user => {
    // create an array to hold JUST the IDs of Address available
    let addressesID = []
    // transfer all Address's ID
    for(let i = 0; i < (user.address).length; i++) {
        // push available address's ID one by one
        addressesID.push(user.address[i]._id)
    }
    // get all address info available in Address (from DB) 
    const addresses = await Address.find(
        { _id: { $in: addressesID } }
    )
    .populate('state')
    .populate('country')
    .then(address => address)
})
.then(all => console.log(all))
.catch(err => res.json({ err }))

然后它将console.log()

{
    _id: '5fabababababababababab1',name: {
        firstName: 'Lalapolalaa',lastName: 'Newb'
    },address: { // populate happens here
        _id: '5fefefefefefefefefef1',addressOne: 'Lot 1,Street 12',addressTwo: 'SS 21',postcode" : '47500',city: 'Subang Jaya',state: { // populate happens here
            _id: '5fghghghghghghghghg1',name: 'Selangor',__v: 0
        },country: { // populate happens here
            _id: '5ijijijijijijijijij1',name: 'Malaysia',__v: 0
    },__v: 0
}

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...