从toObject
的文档中,它指出minimize
选项将删除空对象(默认为true
)
以及toJSON
的文档说明此方法接受与Document#toObject
相同的选项。
但是我注意到有两个例子似乎不是真的(我还没有做过详尽的检查)。
我的主要问题是:我错过了什么(这是预期的输出)还是这个错误?
使用版本3.8.7。
给出简单的模式:
var CommentSchema = mongoose.Schema({
body: String,
created: {
by: {
type: String,
required: true
},
date: {
type: Date,
default: Date.now
}
}
});
var BlogSchema = mongoose.Schema({
title: String,
blog: String,
created: {
by: {
type: String,
required: true
},
date: {
type: Date,
default: Date.now
}
},
comments: [CommentSchema]
});
var Blog = mongoose.model('Blog', BlogSchema);
案例1
Blog.findOne({
_id: id
}, function(err, blog) {
console.log(blog); // causes toJSON to be executed
});
// outputs:
{
title: 'My first blog! #Super',
blog: 'This is my very first #blog! I hope you enjoy it. #WOOHOO',
_id: 532cb63e25e4ad524ba17102,
__v: 0,
comments: [], // SHOULD THIS BE INCLUDED??
created: {
by: 'Joe',
date: Fri Mar 21 2014 17: 59: 26 GMT - 0400(EDT)
}
}
案例2
Blog.findOne({
_id: id
}, 'title', function(err, blog) {
console.log(blog); // causes toJSON to be executed
});
// outputs:
{
title: 'My first blog! #Super',
_id: 532caa3841176afb4a7c8476,
created: {} // SHOULD THIS BE INCLUDED??
}
答案 0 :(得分:0)
首先,我对使用console.log强制执行JSON的理解不正确。为此,请使用:console.log(JSON.parse(JSON.stringify(blog)));
使用正确的方法显示猫鼬文档的JSON表示解决了案例#2:
Blog.findOne({
_id: id
}, 'title', function(err, blog) {
console.log(JSON.parse(JSON.stringify(blog))); // causes toJSON to be executed
});
// outputs:
{
title: 'My first blog! #Super',
_id: 532caa3841176afb4a7c8476
}
但是,仍然会返回#1的空数组:
Blog.findOne({
_id: id
}, function(err, blog) {
console.log(JSON.parse(JSON.stringify(blog))); // causes toJSON to be executed
});
// outputs:
{
title: 'My first blog! #Super',
blog: 'This is my very first #blog! I hope you enjoy it. #WOOHOO',
_id: 532cb63e25e4ad524ba17102,
__v: 0,
comments: [], // SHOULD THIS BE INCLUDED??
created: {
by: 'Joe',
date: Fri Mar 21 2014 17: 59: 26 GMT - 0400(EDT)
}
}
所以我想答案是,如果文档只意味着空对象(而不是数组),那么这是预期的行为。