【问题标题】:Nested populate array of ObjectIdObjectId 的嵌套填充数组
【发布时间】:2021-01-06 01:40:45
【问题描述】:

我正在尝试 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, required: true, 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, required: true },
        // City
        city: { type: String, required: true },
        // 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
    }
    

我知道如何从Address 到populate state 和country,如下所示:-

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

但是我怎么能populateObjectId 的数组。我做了如下所示的代码:-

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",
        "lastName": "Newb"
    },
    "address": [
        {
            "_id": "5fcdcdcdcdcdcdcdcdc1",
            "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   
}

我怎样才能用下面的当前代码得到它(如上所示):-

User.findById({ _id: userId }) // let's say I've the userId
.populate('address') // assuming this populate of address works
.then(async user => {
    // how to populate state & country of Address?
    // code below only return address[0] information (assumption)
    const address = await Address.findById({ _id: user.address[0].addressID._id })
    .populate('state')
    .populate('country')
    .then(address => address)
})
.catch(err => res.json({ err }))

【问题讨论】:

    标签: node.js arrays populate mongoose-populate


    【解决方案1】:

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

    • 在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, required: true, 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);
    

    接下来我可以直接编写如下所示的代码(SOLUTION):-

    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
        },
        __v: 0
    }
    

    【讨论】:

      猜你喜欢
      • 2014-11-05
      • 1970-01-01
      • 2015-03-26
      • 2020-06-07
      • 2021-03-03
      • 2018-07-05
      • 2021-06-06
      • 2019-12-06
      相关资源
      最近更新 更多