Mongoose: TypeError: Cannot read property 'ownerDocument' of null

Created on 30 Dec 2016  Â·  5Comments  Â·  Source: Automattic/mongoose

Intent
Upsert a document

Problem
I got a "TypeError: Cannot read property 'ownerDocument' of null" on function upsertError

Schema
Attached (customer.js.txt)
customer.js.txt

Code snippet

router.post('/cliente', passwordless.restricted(restrictedOptions), function (req, res) {
    req.check('latitude', 'Não foi possível determinar a latitude do endereço especificado').isDecimal();
    req.check('longitude', 'Não foi possível determinar a longitude do endereço especificado').isDecimal();
    req.check('name', 'O nome especificado não é alfanumérico').notEmpty();
    req.check('email', 'O e-mail especificado não é válido').isEmail();
    req.check('address', 'O endereço especificado não é válido').notEmpty();
    req.getValidationResult()
        .then(function checkPostClienteValidationResult (result) {
            if (result.isEmpty()) {
                const customerData = {
                    name: req.sanitize('name').trim(),
                    email: req.sanitize('email').normalizeEmail(),
                    phone: req.sanitize('phone').trim(),
                    address: {
                        coordinates: {
                            type: 'Point',
                            coordinates: [req.sanitize('longitude').toFloat(), req.sanitize('latitude').toFloat()]
                        },
                        streetAddress: req.sanitize('address').trim(),
                        public: ((typeof req.body.address_is_public === 'undefined') ? false : true)
                    },
                    legalId: req.sanitize('legal_id').trim(),
                    notes: req.sanitize('notes').trim()
                };
                const isUpdate = (typeof req.body.id === 'string') && (req.body.id !== '');
                debug('Upserting customer (update: %s), customer data: %j', isUpdate, customerData);
                const updateQuery = {
                    _id: (isUpdate ? req.body.id : mongoose.Types.ObjectId())
                };
                const updateOptions = {
                    upsert: true,
                    runValidators: true,
                    setDefaultsOnInsert: true
                };
                Customer.findOneAndUpdate(updateQuery, customerData, updateOptions)
                    .exec()
                    .then(function upsertDone (customer) {
                        debug('Upsert finished, customer data: %j', customer);
                        var flashMessage;
                        if (isUpdate) {
                            flashMessage = 'O cliente foi atualizado com sucesso';
                        } else {
                            flashMessage = 'O cliente foi adicionado com sucesso';
                        }
                        req.flash(flashMessage);
                        res.redirect(dashboardCustomersPath);
                    }, function upsertError (err) {
                        debug('Customer upsert error: %s', err);
                        for (const key in err.errors) {
                            if (err.errors.hasOwnProperty(key)) {
                                req.flash('danger', err.errors[key].message);
                            }
                        }
                        res.redirect(dashboardCustomersPath);
                    });
            } else {
                res.redirect(dashboardCustomersPath);
            }
        });
});

Notes
Mongoose version: 4.7.5
Nodejs version: 7.3.0

needs clarification

Most helpful comment

Add the context option to your query:

const updateOptions = {
  upsert: true,
  runValidators: true,
  setDefaultsOnInsert: true,
  context: 'query'
};

As specified in the mongoose-unique-validator docs

All 5 comments

Show your schemas please.

They are in the attached file, did you manage to check that out?

Em 31 de dez de 2016 22:10, "Valeri Karpov" notifications@github.com
escreveu:

Show your schemas please.

—
You are receiving this because you authored the thread.
Reply to this email directly, view it on GitHub
https://github.com/Automattic/mongoose/issues/4850#issuecomment-269886877,
or mute the thread
https://github.com/notifications/unsubscribe-auth/AImC8TkB-5uYGkQclhAqUB3sQ1kb34ovks5rNu7ZgaJpZM4LYWh2
.

Add the context option to your query:

const updateOptions = {
  upsert: true,
  runValidators: true,
  setDefaultsOnInsert: true,
  context: 'query'
};

As specified in the mongoose-unique-validator docs

Hi, @vkarpov15 How about the usage of Typescript: there is no context parameter there.
An error comes out as below:

TSError: ⨯ Unable to compile TypeScript
app/service/tools/common.ts (196,9): Argument of type '{ new: true; upsert: true; runValidators: true; setDefaultsOnInsert: true; context: string; }' is not assignable to parameter of type 'ModelFindOneAndUpdateOptions'.
Object literal may only specify known properties, and 'context' does not exist in type 'ModelFindOneAndUpdateOptions'. (2345)

Thanks~

No idea, we don't have formally supported typescript bindings, so report an issue to whoever maintains yours.

Was this page helpful?
0 / 5 - 0 ratings