Mongoose Model.find()参数的问题

我正在研究一个节点应用程序(与IOS前端),并偶然发现这个问题。 我和mongoose一起使用了mongodb。 我有这个路由,/得到接收正确的用户ID,并试图find所有'Voots'具有相同的用户ID。 这是'Voot'的样子:

{ "_id": "59db9fa2659bb30004899f05", "title": "Pizza!", "body": "hoppakeeee", "user": { "__v": 0, "password": "$2a$10$Rwb5n7QoKaFaAOW37V0aWeEeYgfn6Uql474ynUXb83lHi7H2CuB1u", "email": "noelle.schrikker@planet.nl", "name": "Noelle Schrikker", "_id": "59db9ecf659bb30004899f04" }, "__v": 0, "downVotes": [], "upVotes": [] 

},

正如你所看到的,它有一个名为user的属性,它是一个包含名字,电子邮件,密码和_id的用户对象。

我按照我的要求这样做:

 // Send all voots from the specific user Voot.find({"user._id": userId}, function(err, voots) { if (err) { console.log(err); res.status(400).send(err) res.end() } if (voots) { res.status(200).send(voots) res.end() } }) 

我试图find他们的user具有userId属性(这是正确的用户ID)的所有voots。 但是,这是行不通的。 我试图通过"user.email"find它的工作。 我认为这与id之前有关。 任何意见是赞赏!

Voot shema:

 var vootSchema = new mongoose.Schema({ title: String, body: String, user: { type: mongoose.Schema.Types, ref: 'user' }, upVotes: [String], downVotes: [String] }) var Voot = mongoose.model('voot', vootSchema) 

Userschema:

 var userSchema = new mongoose.Schema({ name: String, email: String, password: String }) var User = mongoose.model('user', userSchema) 

我会假设user对象的_id不是一个string。 这就是说你需要修改你的查询来使用ObjectId而不是string:

  Voot.find({"user._id": ObjectId(userId)}, function(err, voots) { if (err) { console.log(err); res.status(400).send(err) res.end() } if (voots) { res.status(200).send(voots) res.end() } }) 

如果您不想更改查询,则可以更改您的user架构,以便_id是string。 然后你的查询应该开始工作:

 var userSchema = new mongoose.Schema({ _id: { type: String }, name: String, email: String, password: String }) var User = mongoose.model('user', userSchema) 

在你的查询中使用user而不是user._id

 Voot.find({ "user": userId }, function(err, voots) { // Callback code }) 

id或引用的用户存储在用户字段中。 用户子文档,因此user._id字段将仅在填充后才可用。

得到它了! 我在Voot模式中添加了ObjectObject,现在我可以使用人口访问User对象。 我现在可以通过使用以下方法findVoot:

 Voot.find({“user”: userId}).populate('user') .exec() 

感谢所有的答案!