I have a collection which has a attribute which references an objectId of another collection.
placeSchema = mongoose.Schema({
name: String,
category: [{ type: Schema.Types.ObjectId, ref: 'categories' }],
facilities: [{ type: Schema.Types.ObjectId, ref: 'facilities' }],
});
the category
ref is an objectId of the categories
collection. The facilities
ref is an array of objectId's of the facilities
collection.
When I populate the attributes, facilities
becomes and array of the facilities
objecrts but category
also becomes an array of one single category
.
Place.find(query).populate('category').populate('facilities').limit(limit).skip(offset).exec(function(err, data){
if (err) return handleError(err);
res.json(data);
});
Here's an example of the above query:
{
"_id": "52ff59be70e8f0dfc8358cb4",
"address": {
"address_1": "Chambers Street",
"city": "Edinburgh",
"postcode": "EH1 1JF"
},
"description": "The National Museum of Scotland brings together our rich Scottish heritage with exciting international collections.",
"loc": {
"lon": -3.188384,
"lat": 55.94772
},
"name": "National Museum of Scotland",
"facilities": [
{
"_id": "53012d5b65b5e9a35efbb214",
"name": "Facility One"
},
{
"_id": "53012d6965b5e9a35efbb215",
"name": "Facility Two"
}
],
"category": [
{
"_id": "52ffbf33605d0c81f36d98e0",
"name": "Museums",
"slug": "museums"
}
]
}
Here's the document as it is in Mongo:
{
"_id" : ObjectId("52ff59be70e8f0dfc8358cb4"),
"address" : {
"address_1" : "Chambers Street",
"city" : "Edinburgh",
"postcode" : "EH1 1JF"
},
"category" : ObjectId("52ffbf33605d0c81f36d98e0"),
"description" : "The National Museum of Scotland brings together our rich Scottish heritage with exciting international collections.",
"facilities" : [
ObjectId("53012d5b65b5e9a35efbb214"),
ObjectId("53012d6965b5e9a35efbb215")
],
"loc" : {
"lon" : -3.188384,
"lat" : 55.94772
},
"name" : "National Museum of Scotland"
}
How do I populate my single category
ref instead of an array?
It makes sense since you in the schema definition have declared the category field to be an array:
category: [{ type: Schema.Types.ObjectId, ref: 'categories' }]
The following should work to not put it in an array (remove the []
):
category: { type: Schema.Types.ObjectId, ref: 'categories' }
That is assuming that you indeed want only one category.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.