使用Mongoose 3.6.4版

假设我有这样一个MongoDB文档:

{
    "_id" : "5187b74e66ee9af96c39d3d6",
    "profile" : {
        "name" : {
            "first" : "Joe",
            "last" : "Pesci",
            "middle" : "Frank"
        }
    }
}

我为用户提供了以下模式:

var UserSchema = new mongoose.Schema({
  _id:    { type: String },
  email:  { type: String, required: true, index: { unique: true }},
  active: { type: Boolean, required: true, 'default': false },
  profile: {
    name: {
      first:    { type: String, required: true },
      last:     { type: String, required: true },
      middle:   { type: String }
    }
  }
  created:    { type: Date, required: true, 'default': Date.now},
  updated:    { type: Date, required: true, 'default': Date.now}
);

我提交了一个表单,它传递了一个名为:profile[name][first],值为Joseph的字段

因此,我只想更新用户的名字,但别管他的姓氏和中间名,我想我应该这样做:

User.update({email: "joe@foo.com"}, req.body, function(err, result){});

但当我这样做时,它会"删除"profile.name.lastprofile.name.middle个属性,我最终得到一个如下所示的文档:

{
    "_id" : "5187b74e66ee9af96c39d3d6",
    "profile" : {
        "name" : {
            "first" : "Joseph"
        }
    }
}

所以它基本上是用req.body.profile覆盖所有的profile,我想这是有道理的.有没有办法不必通过在更新查询中指定my字段而不是req.body来更加明确?

推荐答案

你是对的,Mongoose会将更新转换为$set.但这并不能解决你的问题.在mongodb shell中try 一下,你会看到同样的行为.

相反,要更新单个深度嵌套属性,需要在$set中指定深度属性的完整路径.

User.update({ email: 'joe@foo.com' }, { 'profile.name.first': 'Joseph' }, callback)

Mongodb相关问答推荐

Mongo聚合项目数组交集

如何使用MongoDB对子文档进行条件投影?

使用 multer 在我的 MERN 前端显示 MongoDB 图像的正确语法是什么?

如何对 MongoDB setWindowFields 中当前文档以外的文档进行操作

Mongodb Timeseries / Golang - ['timestamp' 必须存在并包含有效的 BSON UTC 日期时间值]

随着时间的推移在 mongodb 中获得

MongoDB乘以对象值?

MongoDB聚合多条件

删除一对一和一对多引用 - Mongoose

更新文档中的数组时,如何在 MongoDB 和 C# 中使用 $push 更新修饰符

mongoose默认值等于其他值

将 MongoDB 地理空间索引与 3d 数据结合使用

SELECT 字段 AS `anothername` 的 mongodb 等效项

如何在 $lookup Mongodb 的 LocalField 中将字符串转换为 objectId

将数据插入 MongoDB - 没有错误,没有插入

在 URL 中使用 ID(来自 mongo 的 ObjectId)是否安全?

如何在array.NET驱动程序中的元素属性上创建MongoDB MultiKey索引

直接从 URL 查询字符串提供的 mongo 查询有多危险?

如何在java中删除mongodb集合中的所有文档

将日期从毫秒转换为 ISODate 对象