简体   繁体   中英

how to add more fields(in mongoose schema) into a field(which is an array of objects) and these objects are reference to another mongoose schema?

i have a mongoose schema of a user which has a field viewes_posts, which is an array of objects and these objects are reference to another mongoose schema (post). Now i want to add two more fields inside this array of objects .

i tried it this way :

viewed_posts: [
    {
      hits: {type: Number, default: 0},
      actualViewsByUser: {type: Number, default: 0},
      type: mongoose.Schema.Types.ObjectId,
      ref: "Post"
    }
  ]

But when i use User.populate("viewed_posts") function it does not show me "hits" and "actualViewsByUser", instead it only shows the complete fields of post schema.

This is the code where i want to access those fields :

User.findById(req.user._id).populate("viewed_posts").exec(function(err,user){
      if(err) console.log(err);
      else{
        console.log("usre found , now we are going to update the views")
        Post.findOne({slug: req.params.slug},(err,post)=>{
          if(err) console.log(err);
          else{
            user.viewed_posts.push(post);
            user.save();
            let index= 0;
            console.log("viewed_posts.length",user.viewed_posts.length);
            for(var i=0;i<user.viewed_posts.length;i++){
              console.log("post.slug", post.slug)
              console.log("user.viewed_posts.slug", user.viewed_posts[i].slug)
              if(post.slug === user.viewed_posts[i].slug){
                console.log(user.viewed_posts[i]);
                index = i;
                break;
              }
            }
            console.log("index  : ", index);
            console.log("increasing number of hits each time this particular user visits this post");
            console.log("user.viewed_posts.hits before  : " , user.viewed_posts[index].data.hits)
            user.viewed_posts[index].hits +=1;
            console.log("user.viewed_posts.hits after  : " , user.viewed_posts[index].data.hits)
            console.log("increasing number of hits of the post no matter how many times any user visit here");
            console.log("post.views before  : " , post.views)
            post.views +=1;
            console.log("post.views after  : " , post.views)
            if(user.viewed_posts[index].actualViewsByUser != 4){
              console.log("increasing number of actualViews of this post only if this user haven't visited more than 4 times");
              console.log("post.actualViews before  : " , post.actualViews)
              post.actualViews +=1;
              console.log("post.actualViews after  : " , post.actualViews)
              post.save((err,post)=>{
                if(err) console.log(err)
                else console.log("post saved sucessfully",post);
              });
              console.log("user.viewed_posts.actualViewsByUser after  : " , user.viewed_posts[index].actualViewsByUser)
              user.viewed_posts.actualViewsByUser += 1;
              console.log("user.viewed_posts.actualViewsByUser after  : " , user.viewed_posts[index].actualViewsByUser)
            }
            
            
          }
        })
      }
    })

and this is the output :

increasing number of hits each time this particular user visits this post
user.viewed_posts.hits before  :  undefined
user.viewed_posts.hits after  :  NaN
increasing number of hits of the post no matter how many times any user visit here
post.views before  :  0
post.views after  :  1
increasing number of actualViews of this post only if this user haven't visited more than 4 times
post.actualViews before  :  0
post.actualViews after  :  1
user.viewed_posts.actualViewsByUser after  :  undefined
user.viewed_posts.actualViewsByUser after  :  undefined

What can i do to integrate these 2 fields(hits,actualViewsByUser) into this field(viewed_posts)? Any help would be appreciated.

Because you have to specify the fields you want to populate.

User.findById(req.user._id).populate("viewed_posts", "hits actualViewsByUser", Post) // pass in the Post model as well (you'll have to import this).

I pass in the model as I've had errors before because Mongoose didn't populate the fields for me correctly.

However, I'm not sure your approach is the best one. "hits" and "actualViewsByUser" would refer to a specific post via an ID. When you use populate Mongoose will take the id, look for the relevant post, then populate with the appropriate information "hits", "actualViewsByUser", etc. The "hits" and "actualViewsByUser" would need to be stored on your Post model, not your User model.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM