Having problems updating a document that is retrieved using the Mongoose model and processed as a promise

Go to Update # 2 for more details.

I'm having problems simply updating a document retrieved from a container request using the Mongoose model. The request findhas two groups, but other than that, im not sure if the problem could be

The problem I am facing is that when I retrieve the document, update the property, and then try to save the updates in the document using the Mongooses method Doc.save(), nothing happens. It is strange that save () does not even disable the callback passed to it. (Either run then()or catch()if I treat it as a promise)

Model: Asset

module.exports = Mongoose => {
    const Schema = Mongoose.Schema

    const assetSchema = new Schema({
        attributes: [{
            _field: {
                type: Schema.Types.ObjectId,
                ref: 'Field',
                required: true
            },
            value: {
                type: Schema.Types.Mixed,
                required: true
            }
        }],
        _partition: {
            type: Schema.Types.ObjectId,
            ref: 'Partition'
        }
    })

    return Mongoose.model( 'Asset', assetSchema )
}

heres find

[
    {
        "_id" : ObjectId("56b626dc4040b5383696d16f"),
        "_partition" : { 
            _fields: [Object],
            name: 'Server stuff',
            _id: ObjectId("56ae4707f3d4645b2e5b0537")
        },
        "attributes" : [
            {
                _field: {
                    _id: ObjectId("56ae4703f3d4645b2e5b0534"),
                    name: 'Hostname'
                },
                value: 'server-04.foobar.ad',
                _id: ObjectId("56b626dc4040b5383696d172")
            }
        ]
    }
]

, Foo.find ( ) ( ), a.save() . :

Asset
    .find( { _id: '56b6568cb5195902381f6c65' } )
    .populate( { path: 'attributes._field' } )
    .populate( { path: '_partition' } )
    .then( docs => {
        if( ! docs )
            throw new Error(`No docs were found`)

        console.log('# Docs Found:', docs.length) // 1
        console.log('# Instance?:', docs[0] instanceof Asset) // true
        console.log('# Docs:', assets) // Shows single document inside array

        let a = docs[0]

        a.attributes[0].value = 'blah'

        // This is where the problem is, nothing below here is displayed in the console
        a.save(function (err) {
            if (err)
                throw new Error('Failed to update:' + err)

            console.log('Updated!')
        })

    } )
    .catch( err => console.error( 'ERROR:',err ) )
    .finally( () => Mongoose.connection.close() )

, , a.save(). , Updated!.

Mongoose, (a instanceof Foo true), , save() ..

a.save() , , , then catch.

! , - , , .

P.S. / , , ... - ,

P.S.S. FYI, MongoDB

# 1

@JohnnyHK Doc.markModified():

Asset
    .find( { _id: '56b6568cb5195902381f6c65' } )
    .populate( { path: 'attributes._field' } )
    .populate( { path: '_partition' } )
    .then( docs => {
        if( ! docs )
            throw new Error(`No docs were found`)

        console.log('# Docs Found:', docs.length) // 1
        console.log('# Instance?:', docs[0] instanceof Asset) // true
        console.log('# Docs:', assets) // Shows single document inside array

        let a = docs[0]

        a.attributes[0].value = 'blah'

        a.markModified('attributes')

        // This is where the problem is, nothing below here is displayed in the console
        a.save(function (err) {
            if (err)
                throw new Error('Failed to update:' + err)

            console.log('Updated!')
        })

    } )
    .catch( err => console.error( 'ERROR:',err ) )
    .finally( () => Mongoose.connection.close() )

... a.save() ,

# 2

.. , , .

:

// AS A CALLBACK
Asset.find( { _id: '56b6568cb5195902381f6c65' } )
    .populate( { path: 'attributes._field' } )
    .populate( { path: '_partition' } )
    .exec(function (err, doc) {
    if (err) throw new Error(err)

    doc[0].attributes[0].value = 'FOO'

    doc[0].save(function (err) {
        if (err) throw new Error(err)

        console.log('Updated to:',doc[0])

        Mongoose.connection.close()
    })
})

UNSUCCESSFUL:

// AS A PROMISE

import Promise from 'bluebird'
Mongoose.Promise = Promise
// ..
Asset.find( { _id: '56b6568cb5195902381f6c65' } )
    .populate( { path: 'attributes._field' } )
    .populate( { path: '_partition' } )
    .then( doc => {
        doc[0].attributes[0].value = 'FOO'

        doc[0].save(function (err) {
            if (err) throw new Error(err)

            console.log('Updated to:',doc[0])
        })
    })
    .catch( err => {
        throw new Error(err)
    })
    .finally( () => Mongoose.connection.close() )

, , - ,

... - .then() . save()

# 3

github issue ..

, "" , 4.X 3.X...

im ^ 4.3.7, 3.8.35, , script ... , , ​​ .

+4
1

, , , . .value. return doc[0].save(), ,

var mongoose = require('mongoose');
mongoose.Promise = require('bluebird');
// .....


Asset.find( { _id: '56b6568cb5195902381f6c65' } )
    .populate( { path: 'attributes._field' } )
    .populate( { path: '_partition' } )
    .exec()       // Queries aren't full-fledged promises!
    .then( doc => {
        console.log('Before:',doc[0]);
        doc[0].attributes[0].value = 'FOO'

        // Return a promise!
        return doc[0].save(function(err){
            console.log('Updated to:', doc[0]);
        });
    })
    .catch( err => {
        throw new Error(err)
    })
    .finally( () => Mongoose.connection.close() )

.exec(), promises ( ). .save() , , promises ; promises .

+1

Source: https://habr.com/ru/post/1627587/


All Articles