使用findOne更新mongoDB文档中的子字段并保存 [英] Updating a subfield in a mongoDB document using findOne and save

查看:157
本文介绍了使用findOne更新mongoDB文档中的子字段并保存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试更新mongoDB文档中的特定子字段,因此决定先找到有问题的对象,然后保存更新的对象.由于某些原因,保存选项似乎忽略了我的更改.

I'm trying to update a particular subfield in a mongoDB document and have decided to first find the object in question and then save an updated one. For some reason, the save option seems to ignore my changes.

我的集合中有一个对象,它符合以下模式:

I have one object in my collection, and it meets the following schema:

var tschema= mongoose.Schema({
a: Object
})

var t = db.model('tongoose',tschema);
t.findOne({},function(err,obj){
  console.log(obj.a); //yields ['banana',3]     
  obj.a[1]=1; //to make ['banana',1]
  console.log(obj); //yields ['banana',1]

  obj.save(function(err,real){
    console.log(real); //yields ['banana',1]
  });
});

但是当我回到mongoDB并查找保存的对象时,它从不显示任何更改.你能发现我在做什么错吗?

But when I go back to the mongoDB and look up the saved object, it never shows any changes. Can you spot what I'm doing wrong?

非常感谢.

推荐答案

由于您的架构将a定义为通用对象,因此该字段被Mongoose视为Mixed类型,因此您需要将其标记为由调用 markModified save会忽略更改.

Because your schema defines a as a generic object, that field is treated as the Mixed type by Mongoose and you need to mark it as changed by calling markModified or save will ignore the change.

obj.markModified('a');
obj.save(function(err,real){ ...

请参见文档的此页面上有关Mixed类型的讨论.

See the discussion of Mixed types on this page of the docs.

这篇关于使用findOne更新mongoDB文档中的子字段并保存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆