Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
256 views
in Technique[技术] by (71.8m points)

node.js - mongoose populate does not contain documents

I am trying to use populate(), however it seems like it doesn't contain transactions in user.

Is there something wrong in my code? The transaction Table contains userId. Therefore, I thought it would automatically contains array of transactions that matches with the userId.

User Table

enter image description here

Transaction Table

enter image description here

const mongoose = require('mongoose');

const Schema = mongoose.Schema;

const userSchema = new Schema(
    {
        name: 
        {
            type: String,
            required: true
        },
        transactions: [
        {
            type: Schema.Types.ObjectId,
            ref: 'Transaction'
        }
        ],
    },
    {
        timestamps: true
    }
);

module.exports = mongoose.model('User', userSchema)



const mongoose = require('mongoose');

const Schema = mongoose.Schema;

const transactionSchema = new Schema(
    {
        userId: 
        { 
            type: Schema.Types.ObjectId,
            ref: 'User',
            required: true 
        },
        payer: String,
        points: 
        { 
            type: Number, 
            reqruied: true 
        }
    },
    {
        timestamps: true
    }
)

module.exports = mongoose.model('Transaction', transactionSchema)


exports.getUsers = async (req, res, next) => {
    User
        .find()
        //.findOne({ _id: "6009f3d8019a22479cb21a5d"})
        .populate('Transaction')
        .then(user => {
            console.log(user)
        })
}
question from:https://stackoverflow.com/questions/65836418/mongoose-populate-does-not-contain-documents

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

In your User-Schema you've defined the transactions as transactions, so you need to populate it under this name:

User.find()
        .populate('transactions')
        .then(user => {
            console.log(user)
        })

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...