var myschema = new Schema({
name: {type:String, default:'fullname'},
subdoc: {
day1: {type:Array, default:[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]},
day2: {type:Array, default:[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]}
}
});
var mymodel = Mongoose.model('mytest',myschema);
//mongoose 3.5.6: find
mymodel.find({},{'name'}, function(err,docs){
logger.info("---> " + docs);
});
结果:
---> { _id: 512da190ba48050f2e000001, **subdoc: {}**, name: 'fullname' }
仅请求返回name
字段,但此函数始终返回subdoc: {}
。有人可以解释一下吗?
使用mongodb shell,看起来很好
db.mytests.find({},{"name":1})
{ "_id" : ObjectId("512da190ba48050f2e000001"), "name" : "fullname" }
然后我将模型更改为:
var myschema = new Schema({
name: {type:String, default:'fullname'},
subdoc: [
day1: {type:Array, default:[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]},
day2: {type:Array, default:[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]}
] // **note: not {} here**
})
使用相同的mongoose api查找,结果就是我的预期:
--->{ _id: 512da46fffebd24b30000002, name: 'fullname' }
我的问题是:为什么使用前一个模式返回字段'subdoc'?
答案 0 :(得分:0)
根据the docs,看起来好像你有点偏离。
示例:
//命名约翰,只选择“名字”和“朋友”字段,立即执行 MyModel.find({name:/ john / i},'name friends',function(err,docs){})
有了这个,我会做这样的事情:
myModel.find({},'name',callback);
修改强>
解决你的意见:在mongodb控制台中,格式化它的正确方法是{'name':1,'friend':1}。使用:
db.collection.find({},{'name friend'})
会抛出错误。要做到这一点,你可以这样做:
db.collection.find({},{'name':1,'friend':1})
但是,如果您更喜欢这种字段选择方式,那么mongoose也允许您这样做。
myModel.find({},{'name':1,'friend':1},callback);
请参阅:API Docs