node.js - Mongodb更新查询删除除命令中指定字段之外的所有数组字段

标签 node.js mongodb mongoose

我正在使用 Node、MongoDB 和 Mongoose。我检查了 MongoDB 文档 setupdate 。我已经在谷歌上搜索了一个多小时,找到了围绕我的问题的主题,但没有什么明确的。 下面的查询更新了正确的字段,但它也完全删除了数组中我未指定的其他字段。

db.posts.update( 
  { "_id" : { $exists : true }  },
  { $set : { userCreated : { "time" : new ISODate("2013-07-11T03:34:54Z") } } },
  false,
  true
)

这是我尝试修改的架构部分:

},
userCreated: {
  id: { type: mongoose.Schema.Types.ObjectId, ref: 'User' },
  name: { type: String, default: '' },
  time: { type: Date, default: Date.now }
},

结果如下:

},
"userCreated": {
  "time": { ISODate("2013-07-11T03:34:54Z") }
},

最佳答案

您可以使用点符号更新 userCreatedtime 属性并保留其他属性:

db.posts.update( 
  { "_id" : { $exists : true }  },
  { $set : { "userCreated.time" : new ISODate("2013-07-11T03:34:54Z") } },
  false,
  true
)

关于node.js - Mongodb更新查询删除除命令中指定字段之外的所有数组字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17711903/

相关文章:

javascript - 异步等待单元测试问题

node.js - 从 github 拉取后,npm 开发服务器将无法启动

node.js - 如何在 mongodb 中找到整数值的 $regex?

node.js - 可能未处理 CastError : Cast to date failed for value "function now() { [native code] } on Mongoose

node.js - 如何访问 package.json 配置部分?

node.js - Nodeunit:测试函数中的运行时/抛出错误是_silent_

node.js - 蒙戈 : "2d" index and normal index

performance - 为什么 Meteor 需要这么长时间才能在 Heroku 上加载我的数据?

javascript - Mongodb在数组查询中不会得到任何结果

mongoose - 如何在 Node.js 中使用 mongoose-joins