gpt4 book ai didi

mongoose - 在 Mongoose 中填充对象数组

转载 作者:行者123 更新时间:2023-12-04 10:53:54 27 4
gpt4 key购买 nike

我的文档包含一个名为 clients 的字段那应该包含一组客户端ID。

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

我的数据以 JSON 形式传入,我直接将其发送到 Mongo 以创建文档。出于某种原因, 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'
]
}

我必须对我的输入做一些特别的事情才能正确转换吗?

最佳答案

简单的修复。检查传入的数组是否已填充。如果是这样,我会遍历每个并将转换后的 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));

});

}

希望这对其他人有帮助。

关于mongoose - 在 Mongoose 中填充对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14365739/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com