0

.save()从删除了 ed 字段的查询中检索到的 mongoose 文档上的 a是否.select()会导致不完整的文档被写入 mongo 中的文档表示?

如果是这样,这是否意味着我必须要么不使用字段选择,要么.update()单独发布?

例如

Posts
  .findById(someId)
  .select('-body')
  .exec(function(err, post){
    post.edited = Date.now();
    post.save(function(err){
      // will `post` still have the body field if I query for it from the database again?
    })
  })
4

1 回答 1

7

Well, just try :)

// uses streamline.js
var mongoose  = require('mongoose');
var client    = mongoose.connect('mongodb://localhost/test');

var Doc = mongoose.model('Doc', new mongoose.Schema({
  name  : String,
  body  : String
}));

var doc     = new Doc({ name : 'foo', body : 'this is the body' }).save(_);
var result  = Doc.findById(doc._id).select('-body').exec(_);

console.log('R#1', result);

doc.name    = 'new name';
var newdoc  = doc.save(_);

var result2 = Doc.findById(newdoc._id).exec(_);

console.log('R#2', result2);

This prints:

R#1 { name: 'foo', _id: 525506fb23c4904b61000001, __v: 0 }
R#2 { __v: 0,
  _id: 525506fb23c4904b61000001,
  body: 'this is the body',
  name: 'new name' }

So the body property still exists.

The reason why is that .save() for an existing document actually executes an .update() internally.

于 2013-10-09T07:35:33.043 回答