如何用mongodb node.js中的string填充_id字段?

我有两个集合用户和评论。用户有字段:

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} }); 

现在我想知道如何用注释集合中stringtypes的用户_id来填充这2个集合。 先谢谢你

我想你已经可以使用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(); 

希望能帮助到你。

首先,您需要更新您的模式,因为它需要您要填充的集合的引用:

 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而不仅仅是一个string(尽pipe你可以把它看作是一个string)。

然后你可以使用populate()方法:

 Comments.find({}).populate('user_id').exec()