填充时始终返回空数组

时间:2015-08-20 10:38:47

标签: javascript node.js mongodb mongoose

我是NodeJS的新手。我有一个小例子,带有完整目录

|
|----index.js
|----model
   |----user.js
   |----status.js

model / user.js的内容:

var uri = 'mongodb://localhost/demo1';
var db  = require('mongoose').connect(uri),
    Schema = db.Schema;

var UserSchema = new Schema({
    username: String,
    password: String,
    level: Number,
    status: Number,
    statusName: {type: Number, ref: 'Status'}
});

var User = db.model('User', UserSchema);

module.exports = User;

model / status.js的内容

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

var StatusSchema = new Schema({
    name: String,
    id: Number,
    user_status: [{
        type: Number,
        ref: 'User'
    }]
}, {
    collection: 'user_status'
});

var Status = db.model('UserStatus', StatusSchema);

module.exports = Status;

至少,index.js

var User   = require('./model/user');
var Status = require('./model/status');

Status
    .find({})
    .populate('statusName')
    .exec(function (err, data) {
        console.log(data);
    });

当终端运行index.js时,我得到了数据

[{ _id: 55d596852b3d925575644f69,
    id: 1,
    name: 'Active',
    user_status: [] },
  { _id: 55d596902b3d925575644f6a,
    id: 2,
    name: 'Expired',
    user_status: [] },
  { _id: 55d596962b3d925575644f6b,
    id: 3,
    name: 'Locked',
    user_status: [] }
]

为什么user_status属性返回空?写错了什么代码? 抱歉我的英文不好

1 个答案:

答案 0 :(得分:0)

您的StatusSchema不正确。您需要覆盖_id字段,该字段是.populate()查找的字段:

var StatusSchema = new Schema({
    name: String,
    _id: Number,
    user_status: [{
        type: Number,
        ref: 'User'
    }]
}, {
    collection: 'user_status',
    _id: false
});

因此,请将架构和数据更改为从“id”移至“_id”。这意味着您需要删除集合并再次加载它。或者使用其他集合,因为您无法更改集合中存在的_id值。这是不可改变的。