MongoDB / Mongoose $拉(删除)子文档不工作

把我的头撞到键盘上。

只需要删除子文档。 下面的例子在OnCommands中只有一个项目,但是那里可能有很多项目。 我试过find,findbyid,updatebyId,拉一个接一个的东西。 试图通过subdoc的_id和通用searchinMost简单的运行,没有做任何事情没有错误。

如果你能告诉我我做错了什么,我会非常感激,这是我的代码的最后一部分是不工作的。

样本数据:

> 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") } ] 

模型:

 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; 

节点邮政编码:

 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) } ); }); 

由于更新的查询部分,您的代码将无法工作:您想匹配embedded文档的_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) } );