Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

88
Views
Mongoose Populate a field

I have two mongoose schema

var mongoose = require('mongoose');

var Schema = mongoose.Schema;

var itemSchema = new Schema({

    name: {type: String, required: true, max: 25, trim: true},
    price: {type: Number, required: true, trim: true, default: 0},
    tax: {
        type: Schema.Types.ObjectId,
        ref: "Store"
    }
});

module.exports = mongoose.model('Item', itemSchema);

The second Schema

var mongoose = require('mongoose');

var Schema = mongoose.Schema;

var storeSchema = new Schema({
    name: {type: String, required: true, trim: true},
    taxes: [
        {
            name: String,
            rate: Number
        }
    ]
});

module.exports = mongoose.model('Store', storeSchema);

What I want to do is populate the itemSchema tax object with the storeSchema taxes array of object. every time I pushed a new tax object to the taxes array mongoose created an ObjectId. I stored that ObjectId in my itemSchema Tax. I want to use that _id to retrieve the store taxes that matches the itemSchema _id.

I have tried this so far, but I get no in the tax attribute.

Item.find().populate("tax", "taxes").exec(function (err, docs) {
        if (err) return console.error(err);
        console.log(items);
    });
over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

Try this query

Item.find().populate({
    path: 'tax',
    select: 'taxes'
}).exec(function (err, docs) {
    if (err) {
        console.error(err);
    } else {
        console.log(docs);
    }
});
over 4 years ago · Santiago Trujillo Report

0

Item.find().populate(path:"tax", model: )

Mention your item model file name... don't use "" or '' for the file name, simply add the file name.

over 4 years ago · Santiago Trujillo Report

0

Use Item.find().populate("Store", "taxes") instead of Item.find().populate("tax", "taxes").

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!