0
  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”与以前的模式一起返回?

4

1 回答 1

0

根据docs,您似乎有点偏离了。

例子:

// name LIKE john 并且只选择 "name" 和 "friends" 字段,立即执行 MyModel.find({ name: /john/i }, 'name friends', function (err, docs) { })

有了这个,我会做这样的事情:

myModel.find( {}, 'name', 回调);

编辑

解决您的意见:在 mongodb 控制台中,格式化它的正确方法是 {'name':1, 'friend':1}。使用:

db.collection.find({}, {'namefriend'})

会抛出错误。要正确执行此操作,您将执行以下操作:

db.collection.find({}, {'name':1, 'friend':1})

但是,如果您更喜欢这种字段选择方式,猫鼬也允许您这样做。

myModel.find({}, {'name':1, 'friend': 1}, 回调);

请参阅:API 文档

于 2013-02-26T02:42:48.393 回答