Smashing my head into the keyboard over this.
Simply need to remove subdocument. Example below only has one item in OnCommands but there could be a many items there. I have tried find, findbyid, updatebyId, pull, one things after another. Tried by _id of subdoc and by generic searchinMost simple run without doing anything no errors.
I would be so greatful if you can show me what I am doing wrong, it's the last part of my code that isn't work.
Sample Data:
> 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 Post Code:
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) }
);
});
There is currently no method called deleteById() in mongoose. However, there is the deleteOne() method with takes a parameter, filter , which indicates which document to delete. Simply pass the _id as the filter and the document will be deleted.
You can also overwrite Mongoose's default _id with your own _id . Just be careful: Mongoose will refuse to save a document that doesn't have an _id , so you're responsible for setting _id if you define your own _id path.
Mongoose | save() Function The save() function is used to save the document to the database. Using this function, new documents can be added to the database.
Your code won't work because of the query part of your update: you want to match on the embedded document's _id
, not on the main document. So change it to
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) }
);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With