使用Mongoose查询指定嵌套对象的所有值

时间:2019-04-03 21:17:45

标签: node.js mongodb express mongoose

我目前正在尝试使用Mongoose查询MongoDB集合,并且在尝试将此查询转换为可用的Mongoose查询时遇到麻烦。

MongoDB CLI查询为db.events.find({}, {'first.points': 1, '_id': 0})

这很好用,并返回我在命令行中运行它时的期望值,我尝试了几种将其转换为Mongoose查询的方法,到目前为止,我的尝试是:

尝试#1

Events.find({}).populate('first').exec(function(err, events){
    if(err) { console.log(err) }
    console.log(events);
});

这不起作用,并且在启动节点服务器时引发错误Cast to ObjectId failed for value "10" at path "_id" for model "Event"

尝试#2

Event.find({'first.points': "10"}).populate('first').exec(function(err, events)

这不会引发任何错误,并且确实会返回我期望的值,但是我试图返回所有事件的所有first.points值,我似乎无法做到这一点。

尝试#3

Event.find({'first.points': "$all"}).populate('first').exec(function(err, events)

这也不起作用,这是我最近一次尝试解决此问题,这次再次抛出错误,说Cast to number failed for value "$all" at path "first.points" for model "Event"

我不确定要为此尝试什么,我不确定如何返回所有值而不指定要查找的值。

编辑

下面包含事件的模型

var eventsSchema = new mongoose.Schema({
   name: String, // The event name, with data type String
   date: Date, // Date with data type Date
   first: {
       points: Number, // The points awarded to the first place with data type Number
       house: String
   },
   second: {
       points: Number,
       house: String
   },
   third: {
       points: Number,
       house: String
   },
   fourth: {
       points: Number,
       house: String
   }
});

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

此答案的信用额为naga - elixir - jar

Event.find({}, {'first.points': 1, '_id': 0}, function(err, events) {...})

此代码以正确的格式返回我需要的值,没有错误。

注意,为了清楚起见,我已将其转换为箭头功能。箭头功能在此处Event.find({}, {'first.points': 1, '_id': 0}, (err, events) => {...})