Thursday 18 May 2017

How to find through subdocument from another model

I have a model and collection like this.

User.js

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const UserSchema = new Schema({
  name: String,
  email: String, //convert to contacts with type Object
  username: String,
  password: String,
  createdAt: {
    type: Date,
    default: Date.now
  },
  updatedAt: {
    type: Date,
    default: Date.now
  }
});

const User = mongoose.model('user', UserSchema);

module.exports = User;

servers collection

{ 
"_id" : ObjectId("591d3736e562d87e5f7a4435"), 
"name" : "test.snapzio.com", 
"description" : "test", 
"hostname" : "hostname", 
"ipaddress" : "192.168.1.1", 
"status" : "good", 
"updatedAt" : ISODate("2017-05-18T05:55:02.920+0000"), 
"createdAt" : ISODate("2017-05-18T05:55:02.920+0000"), 
"users" : [
    {
        "id" : "591d2fc1f484ce774c1ca58d", 
    }, 
    {
        "id" : "591d2fc1f484ce774c1ca58d", 
    }, 
    {
        "id" : "591d2fdbf484ce774c1ca58e", 
    }
], 
"projects" : [
    ObjectId("591d3079f484ce774c1ca590")
], 
"__v" : NumberInt(0)

}

I want to get the users that matches the record in servers document then render. This is what i did

router.get('/add_project/:id', ensureAuthenticated, (req, res, next) => {
  Server.findById(req.params.id, (err, server) => {
     User.find({ _id: server.users.id }, (err, users) => {
        console.log(users);//undefined

     });
 });

});

I want to get all users that matches the record in server document. Please consider not changing the Schema.



via lawrence bacus

No comments:

Post a Comment