【问题标题】:How to populate _id field with string filed in mongodb node.js?如何在 mongodb node.js 中使用字符串字段填充 _id 字段?
【发布时间】:2018-05-15 06:24:27
【问题描述】:

我有两个集合 user 和 cmets。在 user 中有字段:

const user = mongoose.Schema({
    _id                 :("In the form of ObjectID"), 
                      //ObjectId("5a19086e0664e832842f2c24")
    user_name                   :{type: String},
    password                    : {type: String}
});

和 cmets 集合:

const comments = mongoose.Schema({
    user_id                     :{type: String},
                //"5a19086e0664e832842f2c24" this is user's _id
    comment                    : {type: String}
});

现在我想知道如何使用评论集合中字符串类型的用户 _id 填充这 2 个集合。 提前谢谢你

【问题讨论】:

    标签: node.js mongodb


    【解决方案1】:

    我认为你已经可以像这样使用 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();
    

    希望对你有帮助。

    【讨论】:

    • 是的,没错,但是猫鼬文档建议始终使用 ObjectId,除非有理由不这样做。 Note: ObjectId, Number, String, and Buffer are valid for use as refs. However, you should use ObjectId unless you are an advanced user and have a good reason for doing so,见:mongoosejs.com/docs/populate.html
    【解决方案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()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-04-05
      • 2011-12-23
      • 2017-09-17
      • 2018-09-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多