更新猫鼬中的嵌套对象 [英] Updating nested object in mongoose

查看:63
本文介绍了更新猫鼬中的嵌套对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经搜索了许多关于嵌套对象的问题,但是我发现的所有问题都与数组有关.

I have searched many questions on nested objects, but all I found where related to array[s].

我正在寻找猫鼬中更新的简单嵌套对象.

I am looking for a updating simple nested object in mongoose.

从此处 http://mongoosejs.com/docs/guide.html

there is an example schema :
var blogSchema = new Schema({
  title:  String,
  author: String,
  body:   String,
  comments: [{ body: String, date: Date }],
  date: { type: Date, default: Date.now },
  hidden: Boolean,
  meta: {
    votes: Number,
    favs:  Number
  }
});

创建文档后,

以后如何更改收藏夹号码?

How can I change the favs number later on?

没有我可以找到的相同文件.

There is no document for the same that I could find.

这就是我所做的:

blog.findById(entityId, function(err, mainDoc){
      if(err || !mainDoc) return next(err || 'Document not found');
      var subDoc = mainDoc['meta'];
      if(subDoc){
        subDoc = _.extend(subDoc, { favs : 56 }); //_ lib already available
        console.log(mainDoc.get('meta')); //Prints the updated result with favs = 56  OK
        mainDoc.save(function(err, doc){
           console.log(doc.get('meta')); // prints the updated results with favs = 56 OK
        });
      } else next('Not found');
    });

所有工作文件和所有控制台都会提供所需的结果.

Everything works file and all console gives the desired result.

但是当我切换到猫鼬控制台并查询文档时,我没有得到更新的结果.

But when I switch to mongoose console and query the document, I do not get the updated result.

我知道还有其他方法可以实现相同目的,但是我只是在寻找在此特定代码中做错的事情.

I know there can be other ways to achieve the same, but I am only looking for what I am doing wrong in this particular code.

为什么控制台在保存文档后从数据库中提供了不匹配的数据?

Why the console, after saving document, gives unmatched data from database?

启用猫鼬调试选项后,我发现查询中没有要更新的数据.查询用空白$ set触发. {$ set:{}}

Upon enabling the mongoose debug option, I found the in query there is no such data to be updated. Query fires with blank $set. { $set : {} }

推荐答案

如果只想更改favs的值,则可以使用更简单的查询:

If you just want to change the value of favs, you can use a simpler query:

blog.findByIdAndUpdate(entityId, {$set: {'meta.favs': 56}}, function(err, doc) {
    console.log(doc);
});

这篇关于更新猫鼬中的嵌套对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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