【问题标题】:Update searching by ObjectId in an array of objects在对象数组中按 ObjectId 更新搜索
【发布时间】:2013-10-09 03:11:37
【问题描述】:

业务架构:

var BusinessSchema = new Schema({
    owners: {type: Array},
    templates:[{
        _id : ObjectId,
        title : String,
        path : String,
        custom_navigation : Boolean
    }]
});

业务集合如下所示:

{"owners" : [
        ObjectId("522fa2d61685d3f4ce000002")
    ],
    "templates" : [
        {
            "_id" : ObjectId("524c3bacc7ba62c549000004"),
            "custom_navigation" : true
        },
        {
            "_id" : ObjectId("524c3bacc7ba62c549000005")
        },
        {
            "_id" : ObjectId("524c3bacc7ba62c549000006")
        }
    ]}

更新存储在模板数组中的特定模板的功能:

        var Business = require('../models/business.js');

        Business.update({'owners' : req.user._id, "templates._id" : req.body._id}, {
            $set : {"templates.$.custom_navigation" : req.body.custom_navigation}
        },
        function(err, numUpdated){
            console.log(numUpdated);
            if(numUpdated > 0){
                res.json(200, req.body);
            }else{
                res.json(404);
            }
        });

当我输出update 函数的搜索参数时,我看到了:

{ owners: 522fa2d61685d3f4ce000002,
  'templates._id': '524c3bacc7ba62c549000004' }

注意,Mongoose 似乎将 req.user._id 识别为 ObjectId,但 req.body._id 作为字符串传递。我尝试将其转换为 ObjectId 没有结果。 update 语句总是更新模板数组中的第一项,无论 templates._id 设置为什么。

【问题讨论】:

    标签: node.js mongodb mongoose


    【解决方案1】:

    您需要通过对象 id 进行搜索,而不是通过 req.body._id(我猜它是一个整数)

    var templateId = require('mongoose').Types.ObjectId;
    Business.update({'owners' : req.user._id, "templates" : {$elemMatch :{ _id: new templateId(req.body._id)}}},     
    ....
    

    【讨论】:

    • 我忘了模板是一个数组..我已经修改了答案,请试一试..
    猜你喜欢
    • 2022-12-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-17
    • 1970-01-01
    • 2022-06-16
    • 2021-02-16
    • 2013-04-11
    相关资源
    最近更新 更多