Mongoose 填充ObjectId'的数组;猫鼬
我的文档包含一个名为Mongoose 填充ObjectId'的数组;猫鼬,mongoose,Mongoose,我的文档包含一个名为clients的字段,该字段应该包含一个客户端id数组 { "first_name":"Nick", "last_name":"Parsons", "email":"nick@movementstrategy.com", "password":"foo", "clients":[ "50f5e901545cf990c500000f", "50f5e90b545cf990c5000010" ] } 我的数据是以JSON的形式输入的,我直
clients
的字段,该字段应该包含一个客户端id数组
{
"first_name":"Nick",
"last_name":"Parsons",
"email":"nick@movementstrategy.com",
"password":"foo",
"clients":[
"50f5e901545cf990c500000f",
"50f5e90b545cf990c5000010"
]
}
我的数据是以JSON的形式输入的,我直接将其发送到Mongo以创建一个文档。由于某些原因,客户端
在创建时没有被填充,因此我必须手动将它们作为字符串输入
我的模式相当简单,定义如下:
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));
});
}
希望这对其他人有所帮助。公认的答案可能已经过时了 如果要更新此集合,我建议使用$push更新。此更新方法旨在避免在所有操作都附加到集合中的数组时执行更新
不会推送复制user.clients的内容?如何在地图中填充例如
cid的内容function@PratikBothra否,因为他在循环data.clients时正在推入user.clients。请在mongoose中显示一些示例,以了解您的推荐技巧。可以在提供的链接中找到示例。。这与填充对象数组有什么关系?