I have 2 Schema’s a user and a subscription schema and they are connected, when a user adds a subscription it will be added in the User Schema in a array.
User Model:
const mongoose = require('mongoose');
const bcrypt = require('bcryptjs');
const saltRounds = 10;
const Role = require('../config/roles')
const subscription = require('./subscriptionModel')
const Schema = mongoose.Schema;
const userModel = new Schema({
created: { type: Date, default: Date.now },
updated: { type: Date, default: Date.now},
fullname: {
type: String,
required: true
},
email: {
type: String,
required: true,
unique: true
},
birthDate: {
type: String,
required: true
},
password: {
type: String,
required: true
},
profileImage: {
type: String
},
role: {
type: String,
default: Role.user
},
subscriptions: [subscription.modelName]
})
// hash user password before saving into database
userModel.pre('save', async function save(next) {
if (!this.isModified('password')) return next();
try {
const salt = await bcrypt.genSalt(saltRounds);
this.password = await bcrypt.hash(this.password, salt);
return next();
} catch (err) {
return next(err);
}
});
// Compare passwords when user tries to log in.
userModel.methods.comparePassword = function(candidatePassword, cb) {
bcrypt.compare(candidatePassword, this.password, function(err, isMatch) {
if (err) return cb(err);
cb(null, isMatch);
});
};
module.exports = mongoose.model('User', userModel)
And Subscription Model:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const subscriptionModel = Schema({
name: {
type: String,
required: true,
},
price: {
type: Number,
required: true
},
paymentDate: {
type: String,
required: true
},
active: {
type: Boolean,
default: true
},
created: { type: Date, default: Date.now },
updated: { type: Date, default: Date.now },
users: { type: Schema.Types.ObjectId, ref: 'User' },
}, {
collection: "Subscriptions"
})
module.exports = mongoose.model('Subscriptions', subscriptionModel)
Then i would do something like
userModel.updateOne({
_id: payload.user._id
}, {
$set: {
'subscriptions.0.price': req.body.price
}
}, function (err, result) {
console.log(result)
})
this works but it updates only the first item in an array…
@pjonp i tried findOneAndUpdate but im getting an error, i searched and i know i need to use updateOne …
I’m still searching …