0

Here is code that send array of cards to client.

var cards = Card.find().sort('-created').exec(function (err, cards) {
    if (err) {
        return res.status(400).send({
            message: errorHandler.getErrorMessage(err)
        });
    } else {
        res.json(cards);
    }
});

Model Card have a field "ownerName" (it's empty in database) and "ownerId" (id of some user). For each card I need to find a user by card.ownerId and assign its name to field "ownerName". How can I do it?

goltir
  • 3
  • 1

2 Answers2

0

I presume you already have a User model.If its the case, the just use "sql-join-like" between your Card model and User model as described here Mongoose/mongoDB query joins.. but I come from a sql background.

The "join column" would be ownerId.

Once you get a list of your cards and users, you will be able to assign the user's name to the field ownerName.

Community
  • 1
  • 1
hzitoun
  • 5,492
  • 1
  • 36
  • 43
0

It's best to do it properly and use refs and population

var mongoose = require('mongoose')
  , Schema = mongoose.Schema;

var cardSchema = Schema({
  _id: Number,
  owner: { type: Schema.Types.ObjectId, ref: 'User' },
});

var Card =  mongoose.model('Card', cardSchema);
var cards = Card.find()
  .sort('-created')
  .populate('owner')
  .exec(function (err, cards) {
    //all cards have a 'owner' field populated with the referenced user doc
  });
Creynders
  • 4,573
  • 20
  • 21