1

My schema is shown below :

var productSchema = new Schema({
    name : String,
    likes : [{
        user_id : Schema.Types.ObjectId,
        date : Date
    }]
});

Assume that I have this collection

{ name : A, likes : [ {user_id : id1, date : blahblah}, {user_id : id2, date : balh}] }

{ name : B, likes : [ {user_id : id1, date : blahblah}] }

{ name : C }

then I want to show, following kinda of output by querying it

(with user_id = id1){ name : A, like : 1}, { name : B, like : 1}, { name : C, like : 0}

(with user_id = id2){ name : A, like : 1}, { name : B, like : 0}, { name : C, like : 0}

So to say, i want to add new field, called 'like' here.

If the user_id exists in array(likes), like is 1, if not, should be zero.

Can i make this happen?

2 Answers 2

1

The best way to do it is to have collection of liked products ids in user schema. So when someone like product you have to add userId to the product collection and product id to the user collection. This is common way to implement many to many relations in mongodb. Optional, to increase read performance, you could denormalize product name into user:

var userSchema = new Schema({
    name : String,
    likedProducts : [{
        _id : Schema.Types.ObjectId,
        productName: String
    }]
});

But keep in the mind that denormalization add overhead to write operations. On product name update you will update it in users collection as well.

Sign up to request clarification or add additional context in comments.

2 Comments

likedProducts in your example is just a subdocument, it's not a real collection.
it is not supposed to be separate collection, it just inner array in users collection.
0

For your Schema, you should perform the following query:

db.collection.find({ likes: { $elemMatch: { user_id: idX }}});

This way, you will get the products with entries for idX userId. All the other ones don't have a userId in the likes array. With this method, you need to add the output with 1 and the others not in the output with 0.

You didn't mention if a userId may have different entries within the same array, because that changes the problem.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.