Reputation: 187
I have found strange behavior of array in Node.js
Googling didn't help. Ofc, it may cause of my fatigue. If so, I am sorry.
So, my model
var UserSchema = new mongoose.Schema({
id: mongoose.Schema.ObjectId,
added: {
type: Date,
default: Date.now()
},
displayName: String,
cart: [{
orderNumber: mongoose.Schema.ObjectId,
exposition: Object,
offer: Object,
state: Number,//1 - Unpaid
}],
});
In controller I am trying to loop through cart array
var cartId = new ObjectId(req.body.id);
mongoose.model('User').findById(currentUser.userId, function (err, user) {
var cart = user.cart;
console.log(cart);
var expId = -1;
if (cart) {
for (var i = 0; i < cart.length; i++) {
var cartItem = cart[i];
console.log(cartItem);
if (cartItem._id === cartId) {
console.log("SHIT");
expId = user.cart.exposition._id;
break;
}
}
}
});
I didn't find better solution to find embedded cart in user than loop. So, when I am logging my cart object
console.log(cart);
I am getting correct object and it works ok, but when I am trying to log
console.log(cartItem);
console.log(cart[0]);
I am getting only
[object Object]
[object Object]
What am I doing wrong?
Upvotes: 0
Views: 156
Reputation: 45
Problem:
This problem arises because you are using findById()
which returns result inside the array
According to my knowledge, there can be only one user record inside User
document
Solution:
Use findOne()
which return a single user result, and you can iterate through user.carts
Upvotes: 0
Reputation: 3502
That is the default toString()
for an object. Try
console.log(JSON.stringify(cartItem));
console.log(JSON.stringify(cart[0]));
instead if you want to see the structure of the object.
Upvotes: 3