使用ref和ObjectId

时间:2016-09-25 10:03:14

标签: javascript node.js mongodb mongoose

我有这两个架构

以下是文件floor.js

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var floorSchema = new Schema({
  alias : String,  
  name: String,
  desc: String,
},{timestamps: true});

var floors = mongoose.model('Floor', floorSchema);
module.exports = floors;

在另一个文件facility.js

var mongoose = require('mongoose');
var k = require('./const')
var Schema = mongoose.Schema;


var facilitySchema = new Schema({
  alias : {type: String, required: true, unique: true},
  name: {type: String, required: true},
  desc: String,
  roomType : {type : mongoose.Schema.Types.ObjectId , ref : 'RoomType'},
  floor : {type : mongoose.Schema.Types.ObjectId , ref : 'Floor'},

},{timestamps: true});


var room = mongoose.model('Facility', facilitySchema);
module.exports = room;

我想通过使用Facility Model找到这个来填充它,以便引用ObjectId文档以及我的数据,因为它嵌入了ojectID(我希望数据不是objectID)

以下是app.js中的api终点代码

app.get('/api/op/fetch/room2', function(req, res, next){
var Colle = require('./model/facility');
require('./model/floor');
Colle.find().populate('floor').exec( function (err, data) {
    if (err) {
        return next(err);
    }
    return res.json({status:1, message : data});
});

});

这是json回复

[
{
  "_id": "57e758ea2d6f2b73c70e73c4",
  "updatedAt": "2016-09-25T04:56:10.071Z",
  "createdAt": "2016-09-25T04:56:10.071Z",
  "floor": null,
  "roomType": "57e5c0e29f611985910e6a24",
  "desc": "That big room",
  "name": "Room 101",
  "alias": "RM101",
  "__v": 0
}
]

上面的楼层对象返回null而不是文档中的对象。我该如何解决这个问题。

在下面的Mongo shell上打印

"_id" : ObjectId("57e758ea2d6f2b73c70e73c4"),
"updatedAt" : ISODate("2016-09-25T04:56:10.071Z"),
"createdAt" : ISODate("2016-09-25T04:56:10.071Z"),
"floor" : ObjectId("57e5b9909f611985910e6a1d"),
"roomType" : ObjectId("57e5c0e29f611985910e6a24"),
"desc" : "That big room",
"name" : "Room 101",
"alias" : "RM101",
"__v" : 0

0 个答案:

没有答案