0

I have a web app where users can post items and it returns it in a table format. But I am wanting to create a section where a user can view their individual submissions. I have the first part working correctly. And it does show a list of user items. However when I am trying to only view that one persons submissions no data shows. When I console.log it I am getting my user data but I am not getting the item data. The item data just returns an empty array. I am not sure what all I need to post on here but I am going to show both Schemas and the route for listing the data.

UserSchema:

const UserSchema = new mongoose.Schema({
  username: {
    type: String,
    trim: true,
    unique: true,
    required: true,
    minlength: 3,
    maxlength: 15
  },
  firstName: {
    type: String,
    required: true,
    minlength: 3,
    maxlength: 15
  },
  lastName: {
    type: String,
    required: true,
    minlength: 3,
    maxlength: 15
  },
  email: {
    type: String,
    unique: true,
    required: true
  },
  items: [
    {
      type: mongoose.Schema.Types.ObjectId,
      ref: "Items"
    }
  ],
  isAdmin: {
    type: Boolean,
    default: false
  }
});

UserSchema.plugin(passportLocalMongoose);

module.exports = mongoose.model("User", UserSchema);

ItemSchema:

const ItemSchema = new mongoose.Schema({
  name: {
    type: String,
    required: true,
    minlength: 3,
    maxlength: 20
  },
  description: {
    type: String,
    required: true
  },
  price: {
    type: Number,
    required: true
  },
  image: String,
  noImage: String,
  createdAt: {
    type: Date,
    default: Date.now
  },
  createdBy: {
    id: {
      type: mongoose.Schema.Types.ObjectId,
      ref: "User"
    },
    username: String
  }
});

module.exports = mongoose.model("Items", ItemSchema);

Route:

router.get("/:id", middleware.isLoggedIn, function(req, res) {
  User.findById(req.params.id, function(err, foundUser) {
    if (err || !foundUser) {
      req.flash("error", "Something went wrong");
      res.render("index");
    } else {
      Item.find()
        .where("creadtedBy.id")
        .equals(foundUser._id)
        .exec(function(err, items) {
          if (err || !foundUser) {
            req.flash("error", "Something went wrong");
            res.render("index");
          }
          console.log("user" + foundUser);
          console.log("items" + items);
          res.render("inventory", {
            user: foundUser,
            items: items
          });
        });
    }
  });
});

So, what am I doing wrong here? ... Thanks

Here is the route that joins the user to the item:

router.post("/item/add", middleware.isLoggedIn, (req, res) => {
  User.findById(req.user._id, (err, user) => {
    upload(req, res, err => {
      if (err) {
        req.flash("error", "error uploading image");
        return res.redirect("back");
      }
      var name = req.body.name;
      if (typeof req.file !== "undefined") {
        var image = "/uploads/" + req.file.filename;
      } else {
        image = "/uploads/no-img.PNG";
      }
      var description = req.body.description;
      var price = req.body.price;
      var createdBy = { id: req.user._id, username: req.user.username };
      var newItem = {
        name: name,
        image: image,
        description: description,
        price: price,
        createdBy: createdBy
      };
      Item.create(newItem, (err, newlyCreated) => {
        if (err) {
          return console.log(err);
        } else {
          user.items.push(newlyCreated);
          user.save();
          res.redirect("/products");
        }
      });
    });
  });
});

And here is my user info from mongo:

{
    "_id" : ObjectId("5aea79207c1f272d186ab97a"),
    "items" : [
            ObjectId("5aea793b7c1f272d186ab97b")
    ],
    "isAdmin" : true,
    "username" : "testuser",
    "firstName" : "Test",
    "lastName" : "User",
    "email" : "test@user.com",
    "__v" : 1
 }

And here is the Item data from mongo:

{
    "_id" : ObjectId("5aea793b7c1f272d186ab97b"),
    "createdBy" : {
            "id" : ObjectId("5aea79207c1f272d186ab97a"),
            "username" : "testuser"
    },
    "name" : "Test",
    "image" : "/uploads/no-img.PNG",
    "description" : "Item",
    "price" : 1,
    "createdAt" : ISODate("2018-05-03T02:51:39.818Z"),
    "__v" : 0
}
Neil Lunn
  • 148,042
  • 36
  • 346
  • 317
Darrell
  • 29
  • 6
  • You should start by reading [How do I perform the SQL Join equivalent in MongoDB?](https://stackoverflow.com/q/2350495/2313887) since what you are asking for is a "join" and there are far more efficient ways of doing that. Show the actual documents you expect to match, as this is probably a data type mismatch issue. Show the content "from the `mongo` shell, and NOT `console.log()` from your code. The `mongo` shell shows us the "TRUE" format and type of the data where as "logging" will not. – Neil Lunn May 03 '18 at 02:43
  • Read my comment again where I explicitly said **NOT `console.log()`**. This is `console.log()` output. Go into the `mongo` ( that's the name of the installed program ) shell and pull up those documents again. I'm looking to see if the `ObjectId` values are actually "strings", so we need to see the "shell" output. – Neil Lunn May 03 '18 at 03:01
  • Actually I copied it from compass but it left out the ObjectId for some reason – Darrell May 03 '18 at 03:04
  • Compass is not the mongo shell. The shell comes with mongodb and I explicitly asked for "it's" output and nothing else for a very good reason ( which I have explained twice now ). Please fire it up! and actually copy it's output and nothing else, because I already know what those ouput and it's not of any use to anyone here. – Neil Lunn May 03 '18 at 03:09
  • I apologize for the aggravation, but I do appreciate the help. – Darrell May 03 '18 at 03:25
  • Yeah you have a typo. `"creadtedBy.id"` should be `"createdBy.id"`. I really suggest you actually read the initial link I gave you and especially look for `$lookup`, which is how you do this with modern versions on MongoDB. There will also be reference to `populate()` with mongoose, but that's really kind of superseded since `$lookup` was introduced. – Neil Lunn May 03 '18 at 03:26
  • Dude, ive been at this for 14 hours off working on this. I need to call it quits today and sleep. I’ve stared at my monitor for two hours now trying to find an issue. – Darrell May 03 '18 at 03:29
  • Thanks again pal – Darrell May 03 '18 at 03:30

0 Answers0