Create unique autoincrement field with mongoose [duplicate]

const ModelIncrementSchema = new Schema({ model: { type: String, required: true, index: { unique: true } }, idx: { type: Number, default: 0 } }); ModelIncrementSchema.statics.getNextId = async function(modelName, callback) { let incr = await this.findOne({ model: modelName }); if (!incr) incr = await new this({ model: modelName }).save(); incr.idx++; incr.save(); return incr.idx; }; const … Read more

MongooseError: Model.findOne() no longer accepts a callback at Function

Mongoose dropped support for callbacks from its node.js driver as of version 5.0. You can use async/await instead: module.exports = { data: new SlashCommandBuilder().setName(‘dbtest’).setDescription(‘db test’), async execute(interaction) { try { const data = await testSchema.findOne({ GuildID: interaction.guild.id, UserID: interaction.user.id, }); if (!data) { testSchema.create({ GuildID: interaction.guild.id, UserID: interaction.user.id, }); } if (data) { console.log(data); } … Read more

Mongodb, aggregate query with $lookup

For any particular person document, you can use the populate() function like var query = mongoose.model(“person”).find({ “name”: “foo” }).populate(“projects.tags”); And if you want to search for any persons that have any tag with ‘MongoDB’ or ‘Node JS’ for example, you can include the query option in the populate() function overload as: var query = mongoose.model(“person”).find({ … Read more