node.js - Mongoose 检索我的文档内部数组的 null
问题描述
我有一个集合,其中一个字段是字符串数组。但是当我使用 查询时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 而不是数组对象。
你有什么主意吗?
解决方案
架构类型错误。应该:
garmentSizes: {
type: [
{
type: mongoose.Schema.Types.ObjectId,
ref: 'GS'
}
],
required: false
}
推荐阅读
- javascript - 理解 React useState() 钩子
- c++ - OpenGL在使用sampler2D时显示条纹
- angular - 如何从选定的单选按钮中获取价值?
- spring - Spring如何将带有单位的配置值转换为自然数
- java - DateTimeFormatter - 严格与宽松的意外行为
- c# - 如何使用 Autofac 注册装饰器:“检测到循环组件依赖”
- java - BigDecimal 月利率
- javascript - 将 HttpHeader 添加到静态文件以解决“脚本错误”
- php - 创建发送电子邮件按钮
- react-native - 列出与 react-native 链接链接的包