【问题标题】:Mongoose findOneAndUpdate: Is there a way to update object in subdocument?Mongoose findOneAndUpdate:有没有办法更新子文档中的对象?
【发布时间】:2017-12-21 19:15:42
【问题描述】:

我有一个这样的模型:

// 文档

var programSchema = new Schema({
    name: {
        type: String
    },
    session: [sessionSchema]
}, {
    timestamps: true
});

// 子文档

var sessionSchema = new Schema({
    name: {
        type: String
    },
    info: {
        type: String
    },
    order: {
        type: Number
    }
}, {
    timestamps: true
});

有没有办法访问子文档对象并在存在时编辑,否则创建新的?

我想到了这样的事情:

 router.post('/createsession', function (req, res) {

        var options = { upsert: true, new: true, setDefaultsOnInsert: true };

        var SessionData = req.body.session;

        if (!SessionData.id) {
            SessionData.id = mongoose.Types.ObjectId();
        }

        Program.findOneAndUpdate({ _id: req.body.session.id }, { $push: { session: SessionData } }, options, function (err, session) {
            if (err) {
                return res.status(409).json({
                    success: false,
                    message: 'Error creating/updating session'
                });
            } else {
                return res.status(200).json({
                    success: true,
                    session: session
                });
            }
        });
    });

这只会创建一个新文档。我可以使用相同的查询编辑现有的吗?

【问题讨论】:

  • 为什么不直接将session 设为引用数组?

标签: node.js mongodb express mongoose


【解决方案1】:

这样试试

      var options = { upsert: true};

  Program.findOneAndUpdate({ _id: req.body.session.id }, { $set: {
                   //Set individually values
               name: req.nnae,

              } }, 
               options, function (err, session) {
            if (err) {
                return res.status(409).json({
                    success: false,
                    message: 'Error creating/updating session'
                });
            } else {
                return res.status(200).json({
                    success: true,
                    session: session
                });
            }
        });
    });

【讨论】:

    猜你喜欢
    • 2017-08-13
    • 1970-01-01
    • 2022-01-10
    • 2020-06-25
    • 1970-01-01
    • 1970-01-01
    • 2018-12-16
    • 2016-10-15
    • 2020-08-10
    相关资源
    最近更新 更多