Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

node.js - Updating nested object in mongoose

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.

From here 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
  }
});

Once created a document,

How can I change the favs number later on?

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

This is what I did:

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?

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 : {} }

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...