保存已删除选定字段的Mongoose文档

pau*_*kon 0 mongoose mongodb node.js

.save()从.select()删除了ed字段的查询中检索到的mongoose文档是否会导致将不完整的文档写入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?
    })
  })
Run Code Online (Sandbox Code Playgroud)

rob*_*lep 7

好吧,试试:)

// 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);
Run Code Online (Sandbox Code Playgroud)

这打印:

R#1 { name: 'foo', _id: 525506fb23c4904b61000001, __v: 0 }
R#2 { __v: 0,
  _id: 525506fb23c4904b61000001,
  body: 'this is the body',
  name: 'new name' }
Run Code Online (Sandbox Code Playgroud)

所以该body物业仍然存在.

原因是.save()现有文档实际上是在.update()内部执行的.