Search code examples
node.jsmongooseauto-incrementpopulate

Node JS : Populate auto increment field (Mongoose)


I have two collections, the first is with an auto increment field,

I make a reference in the second collection to the auto increment field, but the find with populate function doesn't return the populated result.

Table1

const mongoose = require("mongoose");
var autoIncrement = require("mongoose-auto-increment");

const table1Schema = mongoose.Schema({
  name: String,
  displayed: { type: Boolean, default: true },
  updatedAt: Date,
  createdAt: Date
});

autoIncrement.initialize(mongoose.connection);
table1Schema.plugin(autoIncrement.plugin, { model: "table1", startAt: 1 });

module.exports = mongoose.model("table1", table1Schema);

table2

const table2Schema = mongoose.Schema({
  categoryId: { type: Number, ref: "table1" },
  displayed: { type: Boolean, default: true }
});

module.exports = mongoose.model("table2", table2Schema);

Query:

var table2_schema = require("../schemas/table2_schema.js");

module.exports.findPopulateFunction = function() {
  table2_schema
    .find({})
    .populate("categoryId")
    .exec(function(err, doc) {
      console.log("err : ", err);
      console.log("docxx : ", doc);
    });
};

Solution

  • The problem is that i am using a script to insert the "_id" field number, I deleted the declaration of the autoincrement and it works successfully