[英]How to find documents in mongoose by populate field?
I have an issue with mongoose. 我的猫鼬有问题。 When I make some field referenced to other collection, I lose ability to search by this field. 当我将某个字段引用到其他集合时,我失去了通过该字段进行搜索的能力。 I don't know how to describe my problem correctly, so look at the examples please. 我不知道如何正确描述我的问题,因此请查看示例。
Schema: 架构:
var PostSchema = new Schema({
title: String,
content: String,
url: String,
author: { type: Schema.ObjectId, ref: 'User'},
mainImage: String,
type: String
});
Query: 查询:
Post.find({author: user._id})
.then(posts => res.send(posts))
.catch(err => res.status(500).send(err))
Returns nothing. 不返回任何内容。 But if I change "author" field to String, it will works, but without populate. 但是,如果我将“作者”字段更改为“字符串”,它将起作用,但不会填充。 :( :(
Upd: I can't believe. Upd:我不敢相信。 I made this: 我做的:
var PostSchema = new Schema({
title: String,
content: String,
url: String,
author: {type: String, ref: 'User'},
mainImage: String,
type: String
});
Just change type to string. 只需将类型更改为字符串即可。 Omg I can't figure out how it working. 天哪,我不知道它是如何工作的。 How mongoose knows which field I need to compare in ref collection? 猫鼬如何知道我需要在引用集合中比较哪个字段? I mean there is no direct link to "_id" field (see query). 我的意思是没有直接链接到“ _id”字段(请参阅查询)。 Can someone explain? 有人可以解释吗?
Upd2: UPD2:
Auhtor schema: Auhtor模式:
var UserSchema = new Schema({
id: String,
about: String,
firstname: String,
lastname: String,
email: String,
avatar: String,
city: String,
country: String,
dateOfBirth: String,
password: String,
},
{
timestamps: true
})
As you can see, I using additional "id" field just in purpose to give users simple numeric id for url (/id1 etc). 如您所见,我使用附加的“ id”字段只是为了向用户提供url(/ id1等)的简单数字ID。 But I am sure this isn't the source of the problem :) 但是我确定这不是问题的根源:)
尝试改变type: Schema.ObjectId
到type: mongoose.Schema.Types.ObjectId
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.