mongodbmongoose

How to create in mongoose if not exists but not update


I've only found ways to create OR update a document. I need to create if not exists but do nothing if it already exists. How to do it in mongoose?

Please note that findOneAndUpdate won't work, because if it fins the document, it updates it! I don't want that.

UPDATE:

I just want to create a variable called order_number that can be incremented. However, to increment, I must make sure the document exists. However, I cannot update its value in case it exists.

I tried:

let r = await OrderNumber.findOneAndUpdate({ unique: 0 }, { unique: 0, order_number: 0 }, { upsert: true });

It successfully creates when it does not exist, but always updates order_number to 0. I don't want this to happen.


Solution

  • As only way I've found it via two DB calls as in general inserts doesn't have any filters unless findOneAnd* or upsert on updates are used - which we're not looking at. Then only option is to make two calls, here is basic code, please wrap those in proper function & try/catch to add error handling :

    const mongoose = require('mongoose')
    const Schema = mongoose.Schema;
    
    const orderNumberSchema = new Schema({
        any: {}
    }, {
        strict: false
    });
    
    const OrderNumber = mongoose.model('order_number', orderNumberSchema, 'order_number');
    
    let resp = await OrderNumber.findOne({ unique: 0 });
    
    if (!resp) {
        let orderNumberObj = new OrderNumber({ unique: 0, order_number: 0 })
        let r = await orderNumberObj.save();
    }