[英]How to populate _id field with string filed in mongodb node.js?
我有两个集合用户和注释。在用户中有字段:
const user = mongoose.Schema({
_id :("In the form of ObjectID"),
//ObjectId("5a19086e0664e832842f2c24")
user_name :{type: String},
password : {type: String}
});
和评论集:
const comments = mongoose.Schema({
user_id :{type: String},
//"5a19086e0664e832842f2c24" this is user's _id
comment : {type: String}
});
现在,我想知道如何用用户的_id(在注释集合中为字符串类型)填充此2集合。 先感谢您
首先,您需要更新架构,因为它需要引用要填充的集合:
const user = mongoose.Schema({
user_name: { type: String },
password: { type: String }
});
const comments = mongoose.Schema({
user_id: { type: Schema.Types.ObjectId, ref: 'User' },
comment: { type: String }
});
注意: 我删除了_id字段,因为它将自动添加。 还要注意, _id
不仅是字符串,而且是一个ObjectId
(即使您可以将其视为字符串)。
然后可以使用populate()
方法:
Comments.find({}).populate('user_id').exec()
我认为您已经可以使用String来填充这样的ObjectId:
const user = mongoose.Schema({
user_name : {type: String},
password : {type: String}
}); // users._id will natively be an ObjectId
const comments = mongoose.Schema({
user_id : {type: String, ref:'users'}, // user_id has to be referenced with your "users" model
comment : {type: String}
});
Comment.find({}).populate('user_id').exec();
希望能帮助到你。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.