【问题标题】:How to update and Push in mongoose如何更新和推送猫鼬
【发布时间】:2022-12-22 22:05:26
【问题描述】:

我从Here 获取了这个模式

var mongoose = require('mongoose');

var ContactSchema = module.exports = new mongoose.Schema({
  name: {
    type: String,
    required: true
  },
  phone: {
    type: Number,
    required: true,
    index: {unique: true}
  },
  messageCount: {
    type: Number,
    required: true,
    default:0
  },
  messages: [
  {
    title: {type: String, required: true},
    msg: {type: String, required: true}
  }]
}, {
    collection: 'contacts',
    safe: true
});

我可以通过这样做来推送消息

let result = await Contact.findByIdAndUpdate(
        id,
        {$push: {"messages": {title: title, msg: msg}}},
        {new : true})

但我也想在单步中增加 messageCount

messageCount can be random also but point is to push and update

我期待 message 和 messageCount 使用任何 mongoose 函数在单个查询中更新

【问题讨论】:

    标签: node.js mongodb mongoose mern


    【解决方案1】:

    在查看This Post 并尝试解决我的疑问之后

    let result = await Contact.findByIdAndUpdate(
            id,
            {
               messageCount:10
               $push: {"messages": {title: title, msg: msg}}
            },
            {new : true})
    

    【讨论】:

      猜你喜欢
      • 2016-05-25
      • 2019-11-02
      • 2019-10-13
      • 1970-01-01
      • 2016-01-29
      • 2012-03-28
      • 2012-05-18
      • 1970-01-01
      • 2018-10-31
      相关资源
      最近更新 更多