How to set a objectId property in mongoose?

I have a schema named as Message like below;

Message = new Schema({
    id: Number,
    sender: ObjectId,
    receiver: ObjectId,
    date: Date,
    content: String,
    type: Number
});

And a User schema like below;

User = new Schema({
 id: Number,
 username: String,
 isOnline: Boolean
});

I would like to set the sender and receiver properties of message item when a new message is received. When a message is received I am creating a new Message document and setting its properties. But I do not know how to set sender and receiver properties (which should be a reference to an entity in User document). The code I'm using is like below. You can judge the code as much as you want, that's what I would like to. I do not know the right way to get rid of it. But it seems that this is not the one. When I'm using the code below I could not see the sender and receiver properties are set. I think that it could be because findOne is async (I do not know if it is).

var m = new Message();
m.content = messageData.text;
m.id = messageId;
User.findOne({id: socket.userId}, function (e, o) {
  m.sender = o;
});

User.findOne({id: messageData.userId}, function (e, o) {
  m.receiver = o;
});

m.save(function (e) {
  if (!e) {
    console.log("message is saved to the mongodb...");
  }
});

It would be great that if you can tell the right way to do this.

Thanks in advance.

You're almost there. You are correct that findOne is async. You just need to get a handle on their callbacks and save the message after they both respond. Here is a typical pattern you can use:

var m = new Message();
m.content = messageData.text;
m.id = messageId;
User.findOne({id: socket.userId}, function (e, o) {
  if (e) return handleError(e); // assuming you want to handle errors somehow
  m.sender = o;
  m.sender && m.receiver && save();
});

User.findOne({id: messageData.userId}, function (e, o) {
  if (e) return handleError(e); // assuming you want to handle errors somehow
  m.receiver = o;
  m.sender && m.receiver && save();
});

function save () {
  m.save(function (e) {
    if (e) return handleError(e);
    console.log("message is saved to the mongodb...");
  });
}