【问题标题】:mongoose update with push operations on array and set operation on object猫鼬更新与对数组的推送操作和对对象的设置操作
【发布时间】:2015-05-31 21:15:23
【问题描述】:

我有这个猫鼬模式

var ContactSchema = module.exports = new mongoose.Schema({
  name: {
    type: String,
    required: true
  },
  phone: {
    type: Number,
    required: true,
  },
  messages: [
  {
    title: {type: String, required: true},
    msg: {type: String, required: true}
  }],
  address:{ city:String,
            state:String
  }
});

我最初的收藏集包含姓名和电话字段。我需要用新消息将集合更新到消息数组中,并将新地址更新到地址对象中。该函数还必须处理任何单个操作,即在某些情况下我只更新消息数组或更新名称和地址。那么我怎样才能在一个函数中完成所有操作。

        var messages= {
            title: req.body.title,
            msg: req.body.msg
        }
        Model.findOneAndUpdate({'_id': req.body.id,},{$push: {messages:message}},{upsert: true}, function (err, data) {
            if (err) {
                return res.status(500).send(err);
            }
            if (!data) {
                return res.status(404).end();
            }
            return res.status(200).send(data);
        });

【问题讨论】:

  • 你能展示一下你到目前为止所做的尝试吗?
  • 目前我使用不同的更新和发布功能做了同样的事情。
  • 如果您至少可以编辑您的问题并包含您迄今为止所做的部分,那就太好了。
  • 更新问题。这就是我到目前为止所做的

标签: arrays node.js mongodb mongoose


【解决方案1】:

您可以尝试在更新对象中同时使用$set$push 运算符。例如,假设您想在一个操作中同时更新名称和地址字段,对名称字段使用$set,对地址数组使用$push 操作:

var messages= {
    title: req.body.title,
    msg: req.body.msg
},
query = {'_id': req.body.id},
update = {
    $set: {name: req.body.name},
    $push: {messages: message}
},
options = {upsert: true};

Model.findOneAndUpdate(query, update, options, function (err, data) {
    if (err) {
        return res.status(500).send(err);
    }
    if (!data) {
        return res.status(404).end();
    }
    return res.status(200).send(data);
});

【讨论】:

  • 谢谢。如何使用相同的函数处理消息数组中的新值推送和现有值更新?
猜你喜欢
  • 2021-07-06
  • 1970-01-01
  • 2016-02-28
  • 1970-01-01
  • 1970-01-01
  • 2015-03-03
  • 2020-06-30
  • 1970-01-01
相关资源
最近更新 更多