node.js - MongoDB/Mongoose $pull(删除)子文档不起作用

标签 node.js mongodb mongoose

为此把我的头撞到键盘上。

只需要删除子文档。下面的示例在 OnCommands 中只有一个项目,但那里可能有很多项目。我试过 find、findbyid、updatebyId、pull,一个接一个。通过子文档的 _id 和通用搜索进行了尝试最简单的运行没有做任何事情没有错误。

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

示例数据:

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

Node 邮政编码:

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

});

最佳答案

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

关于node.js - MongoDB/Mongoose $pull(删除)子文档不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34884991/

相关文章:

javascript - 在 promise 中链接三个查询

javascript - 如何将数组分割成 block ,但让它一个接一个地填充每个数组

mongodb - Mongoid 没有服务器可用匹配首选项

javascript - 过滤 MongoDB 中的深层填充字段

node.js - 如何将vue-cli开发模式与服务端api结合起来?

node.js - 使用发布者确认 RabbitMQ,在什么情况下发布者会收到成功/失败的通知?

使用存储库模式时的 MongoDB 和大型数据集

javascript - 如何简化mongodb集合?

javascript - 删除项目mongodb和 Node 异步

node.js - Mongoose 仅​​返回文档嵌套数组中的一个元素