MongoDB / Mongoose $ pull (delete) Sub Document not working

Waving your head on the keyboard over it.

Just need to delete the subdocument. The example below contains only one element in OnCommands, but there can be many elements. I tried to find, find, update, pull, one thing after another. Tried _id subdoc and generic search. A simple run without any errors.

I would be so kind if you could show me what I am doing wrong, this is the last part of my code that does not work.

Data examples

> db.EntryPoints.find({_id: ObjectId("569e4fabf1e4464495ebf652")}).pretty()
{
        "__v" : 0,
        "_id" : ObjectId("569e4fabf1e4464495ebf652"),
        "name" : "bbbb",
        "offCommands" : [ ],
        "onCommands" : [
                {
                        "data" : "11111",
                        "operation" : "on",
                        "command" : "ISY-HTTPGet",
                        "_id" : ObjectId("569e4faff1e4464495ebf653")
                }
        ]

Model:

var mongoose = require('mongoose');
var Schema = mongoose.Schema,
    ObjectId = Schema.ObjectId;

var onCommandsSchema = new Schema({
    command: String
    ,operation: String
    ,data: String
})

var offCommandsSchema = new Schema({
    command: String
    ,operation: String
    ,data: String
})

mongoose.model('onCommands', onCommandsSchema);
mongoose.model('offCommands', offCommandsSchema);

// create a schema
var EntryPointsSchema = new Schema({
    name: String
    ,onCommands: [onCommandsSchema]
    ,offCommands: [offCommandsSchema]
    ,description: String
}, { collection: 'EntryPoints' });
mongoose.model('EntryPoints', EntryPointsSchema);


var EntryPoints = mongoose.model('EntryPoints');

module.exports = EntryPoints;

Node Postcode:

router.post('/webservices/removeCommand', function (req, res) {
    var EntryPoints = require('../data_models/automate_entrypoints.js');

    EntryPoints.update(
        { _id: ObjectId(req.body._id) }
        , {
            $pull: {
                onCommands: { id_: req.body._id }
            }
        }
        , function (err, ouput) { console.log("data:", numAffected) }
    );  

});
+4
source share
1 answer

- : _id, .

var EntryPoints = require('../data_models/automate_entrypoints.js');

EntryPoints.update(
    { "onCommands._id": req.body._id }, 
    {
        "$pull": {
            "onCommands": { "_id": req.body._id }
        }
    }, 
    function (err, numAffected) { console.log("data:", numAffected) }
);  
+5

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


All Articles