MongoDB - 使用Mongoose模式 - 如何告诉Mongoose不要保存特定字段

时间:2021-07-22 19:31:23

Say I have a Mongoose schema that looks like this:

假设我有一个看起来像这样的Mongoose架构:

userSchema = mongoose.Schema({
        username: {
            type: String,
            isUnique: true,
            required: true
        },
        teamSnap: {
            username: String,
            password: String
        },
        password: {
            type: String,
            required: true
        },
        linkedin_id: Number,
        email: {
            type: String,
            required: true
        },
        numberOfLineupsCreated: Number,
        hasPaidAlready: Boolean,
        longitude: Number,
        registered_at: {
            type: Date,
            default: Date.now
        },
        created_at: {
            type: Date,
            default: Date.now
        },
        updated_at: {
            type: Date,
            default: Date.now
        }
    });

how do I tell Mongoose NOT to save/store the teamSnap field in the database?

我怎么告诉Mongoose不要在数据库中保存/存储teamSnap字段?

2 个解决方案

#1


1  

You could redefine the toJSON() method and remove your field there:

您可以重新定义toJSON()方法并删除您的字段:

UserSchema.methods.toJSON = function() {
    var obj = this.toObject()
    delete obj.teamSnap

    return obj
}

#2


1  

If you don't need to persist a field in the database why do you need in your model class ?

如果您不需要在数据库中保留字段,为什么在模型类中需要?

You can add it later to the object that you query from MongoDB.

您可以稍后将其添加到从MongoDB查询的对象中。

db.users.findOne({id: id}, function(err, user) {
  user.teamSnap = value
});

#1


1  

You could redefine the toJSON() method and remove your field there:

您可以重新定义toJSON()方法并删除您的字段:

UserSchema.methods.toJSON = function() {
    var obj = this.toObject()
    delete obj.teamSnap

    return obj
}

#2


1  

If you don't need to persist a field in the database why do you need in your model class ?

如果您不需要在数据库中保留字段,为什么在模型类中需要?

You can add it later to the object that you query from MongoDB.

您可以稍后将其添加到从MongoDB查询的对象中。

db.users.findOne({id: id}, function(err, user) {
  user.teamSnap = value
});