Reputation: 2923
This is my user model so you guys can get an idea of my database structure.
var userSchema = new Schema({
firstName: {type: String, required: true, trim: true},
lastName: {type: String, required: true, trim: true},
address: {
street: {type: String, required: true, trim: true},
city: {type: String, required: true, trim: true},
state: {type: String, min: 2, max: 2, required: false},
zipCode: {type: String, required: true, trim: true},
},
companies:[
{
type: Schema.Types.ObjectId,
ref: 'Company',
required: true
}
],
edited: {type: Date},
created: {type: Date, default: Date.now}
});
I'm trying to get the user and the companies related to that user. which im getting with this.
router.post('/', function(req, res){
var email = req.body.email;
var password = req.body.password;
User.findOne({email: email, password: password, active: true})
.populate('companies')
.exec(function(err, user){
if(err){
throw err;
}
else if (!user) {
//user wasn't found
res.render('/', {validation: "Invalid Email Or Password"})
}
else {
user.companies = user.companies[0];
console.log(user);
res.end();
}
});
});
when in the console.log(user) i'm getting this output:
{
firstName: 'firstName',
lastName: 'lastName'
companies:[{object}]
}
now the problem with my code is that im saying that the companies array should be an object in this line of code.
user.companies = user.companies[0];
my question is how can I make the console output be like this.
{
firstName: 'firstName',
lastName: 'lastName'
companies:{object}
}
Upvotes: 1
Views: 1109
Reputation: 4066
It seems that user
variable is immutable, you can create another object and copy its data to new object
var _user = {
firstName: user.firstName,
lastName: user.lastName
companies: user.companies[0]
}
simply use toObject()
function to convert mongodb object to plain object, so you can modify it
user = user.toObject()
Upvotes: 2