You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Mongoose中单次查询完成消息推送与messageCount更新?

解决方案

你可以在findByIdAndUpdate的更新参数里同时使用$push和$set(或$inc,按需选择)操作符,实现单次查询完成两个字段的更新:

1. 自定义设置messageCount为固定值

如果需要把messageCount设置为某个指定数值,使用$set:

let result = await Contact.findByIdAndUpdate(
  id,
  {
    $push: { "messages": { title: title, msg: msg } },
    $set: { "messageCount": 自定义数值 } // 替换为你需要的具体数值
  },
  { new: true }
);

2. 对messageCount进行增量更新

如果需要在原有数值基础上增减(比如新增消息时计数+1),使用$inc:

let result = await Contact.findByIdAndUpdate(
  id,
  {
    $push: { "messages": { title: title, msg: msg } },
    $inc: { "messageCount": 1 } // 这里的1可替换为任意增量,负数即为减量
  },
  { new: true }
);

原ContactSchema参考

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

内容的提问来源于stack exchange,提问作者Bhupender Singh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 01:55:20