我有一个集合,其中的一个字段是字符串数组。但是当我用find()
查询时,它返回null
,而在MongoDB Compass中我可以看到它。
这是我的文档:
{
"_id":"5d4894f23f86a41b84303795",
"position":1,
"garmentTitle":"My first Garment",
"garmentURL":"www.firstgarment.com",
"garmentPictureURL":"/images/first.png",
"brand":"5d49e60e4eface2a00ac58d7",
"garmentMaker":"5d49e8854eface2a00ac58d9",
"garmentPurpose":"5d49e8754eface2a00ac58d8",
"gender":"5d37546f2f8c280adc60b3fe",
"garmentCategory":"5d3a4c7f447a7a3afc71a746",
"fabricComposition":null,
"garmentSizes":["5d4d211f0fe9591facb9a268"] // <<== This is mentioned array
}
这是我定义的架构:
var mongoose = require('mongoose');
var gardataSchema = new mongoose.Schema({
position: {
type: Number,
unique: true,
required: true
},
garmentTitle: {
type: String,
unique: true,
required: true
},
garmentURL: {
type:String,
required:false
},
garmentPictureURL: {
type: String,
required:false,
},
brand:{
type: mongoose.Schema.Types.ObjectId,
ref: 'BR',
required: false
},
garmentMaker: {
type: mongoose.Schema.Types.ObjectId,
ref: 'GM',
required: false
},
garmentPurpose: {
type: mongoose.Schema.Types.ObjectId,
ref: 'GP',
required: false
},
garmentSizes: [{
type: mongoose.Schema.Types.ObjectId,
ref: 'GS',
required: false
}],
gender: {
type: mongoose.Schema.Types.ObjectId,
ref: 'GN',
required: false
},
garmentCategory: {
type: mongoose.Schema.Types.ObjectId,
ref: 'GC',
required: false
},
fabricComposition: {
type: mongoose.Schema.Types.ObjectId,
ref: 'FC',
required: false
},
});
var collectionName = 'garmentData';
mongoose.model('GD', gardataSchema, collectionName);
这是我的控制器:
module.exports.getOneGarmentDataByID = function (req, res) {
GD.find({_id:req.params.id})
.exec()
.then(result => {
res.status(200).json(result);
})
.catch(err => {
console.log(err);
res.status(500).json({error:err});
});
}
请求的路线:
http://localhost:3000/gar/getonegarmentdatabyid/5d4894f23f86a41b84303795
最终结果是:
[
{
"garmentSizes": null, <<== returns null!!!
"_id": "5d4894f23f86a41b84303795",
"position": 1,
"garmentTitle": "My first Garment",
"garmentURL": "www.firstgarment.com",
"garmentPictureURL": "/images/first.png",
"brand": "5d49e60e4eface2a00ac58d7",
"garmentMaker": "5d49e8854eface2a00ac58d9",
"garmentPurpose": "5d49e8754eface2a00ac58d8",
"gender": "5d37546f2f8c280adc60b3fe",
"garmentCategory": "5d3a4c7f447a7a3afc71a746",
"__v": 0,
"fabricComposition": null
}
]
如您所见,它返回null而不是数组对象。
你有什么主意吗?
答案 0 :(得分:1)
模式类型错误。应该是:
garmentSizes: {
type: [
{
type: mongoose.Schema.Types.ObjectId,
ref: 'GS'
}
],
required: false
}