在Mongoose中填充ObjectId数组

7

我的文档包含一个名为clients的字段,它应该包含客户端id的数组。

{
  "first_name":"Nick",
  "last_name":"Parsons",
  "email":"nick@movementstrategy.com",
  "password":"foo",
  "clients":[
    "50f5e901545cf990c500000f",
    "50f5e90b545cf990c5000010"
  ]
}

我的数据以JSON格式传入,我直接将其发送到MongoDB以创建文档。但出现了问题,当我创建文档时,clients 字段未被填充,因此我必须手动输入字符串。

我的模式相当简单,定义如下:

var userSchema = new Schema({
    first_name: {
        type: String,
        trim: true
    },
    last_name: {
        type: String,
        trim: true
    },  
    email: {
        type: String,
        trim: true,
        lowercase: true,
        index: true,
        unique: true,
        required: true
    },
    password: String,
    clients: [Schema.Types.ObjectId]
});

据我理解,我正确地定义了客户端。但是当我进行创建时,无法使客户端数组填充。即使传递给mongo的原始对象看起来很好。

{ 
    first_name: 'Zack',
    last_name: 'S',
    email: 'zack@movementstrategy.com',
    password: 'test',
    clients: [
       '50f5e901545cf990c500000f', 
       '50f5e90b545cf990c5000010' 
    ] 
}

我需要特别处理我的输入内容才能正确转换吗?

2个回答

10

简单修复。检查传入的数组是否已填充。如果是,则循环遍历每个元素并将转换后的ObjectId版本推入该数组。显然,mongoose.Types.ObjectId('STRING');能够将一般字符串转换为有效的mongoose id。

// if clients was passed with associated client ids
if (data.clients.length > 0) {

    _.map(data.clients, function(cid) {

        // push client id (converted from string to mongo object id) into clients
        user.clients.push(mongoose.Types.ObjectId(cid));

    });

}

希望这能帮助到其他人。


1
用户.客户端的内容不会重复推送吗? - Pratik Bothra
我该如何在您的映射函数中填充例如cid这样的内容? - Shailesh Shekhawat
@PratikBothra 不行,因为他正在循环 data.clients 时将其推入 user.clients。 - Rob Evans

1

请提供一些使用Mongoose实现你的推荐技术的示例。 - Steve.NayLinAung
1
示例可以在提供的链接中找到: http://docs.mongodb.org/manual/reference/operator/update/push/#examples - Michael Leanos
这与填充ObjIds数组有什么关系? - Suhayb

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接