我有两个mongodb集合,并且已经在Mongoose中定义了架构。基本上,file.fileSchema是文件名,例如。“ whatever.txt”和(fileCatSchema.path)是路径,例如。“ c:/ text /”。
var fileSchema = new Schema({
name : String,
file : String,
cat_id : [{ type: ObjectId, ref: 'fileCategories' }]
});
var fileCatSchema = new Schema({
branch : String,
file : String,
path : String
});
在我的API中,我已成功填充了具有文件类别(fileCatSchema)的文件,并希望根据请求返回到/ api / files /的完整路径,但是当我实际尝试访问填充的json数据内的属性时,它将作为未定义返回。谁能解释这里发生了什么?在不同的环境(例如chrome的控制台)中执行相同的过程会给我我想要的数据。
api.get('/files/', function(req, res) {
apiModel.files
.find({})
.populate('cat_id')
.exec(function(err, data) {
for(var i=0; i < data.length; i++){
if(data[i].file){
console.log(data[i].cat_id)
/*This returns the array with the data i want:
[{"_id":"55d5e588dfd76d1dec880cd0",
"branch":"complete",
"name":"Frequently Accessed Files",
"path":"complete/faf/","cat_id":[]
}] */
console.log(data[i].cat_id[0].path);
/*But this returns undefined and I have no idea why*/
}
}
if (err) res.send(err);
res.json(data);
});
});
我找到了答案!我不处理常规对象。我遍历了对象的属性,发现Mongoose添加了许多内容,包括一种方法“ toJSON”。我的快速解决方案是使用此方法:
api.get('/files/', function(req, res) {
apiModel.files
.find({})
.populate('cat_id')
.exec(function(err, data) {
//Add Project category path to API
for(var i=0; i < data.length; i++){
if(data[i].file){
var fullPath = data[i].cat_id[0].toJSON().path + data[i].file;
data[i].file = fullPath;
}
}
if (err) res.send(err);
res.json(data);
});
});
更新:现在我明白了我首先要问的问题。lean()方法返回精简后的结果:精简JSON对象。将猫鼬文档转换为json
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句