Mongodb fill method not working

Here is my code for the models

var postSchema = new mongoose.Schema({
created_by: {type: Schema.ObjectId, ref:'User', autopopulate: true },       //should be changed to ObjectId, ref "User"
created_at: {type: Date, default: Date.now},
text: String
});

var userSchema = new mongoose.Schema({
    username: String,
    password: String, //hash created from password
    created_at: {type: Date, default: Date.now}
});

      

Below is the code of how I am inserting data and trying to recover it using the fill method.

Post.create({text: 'farheen123',created_by: '5587bb520462367a17f242d2'}, function(err, post){
if(err) console.log("Farheen has got error"+err);
else console.log(post);
});

      

// 5587f5556e6f2b38244d02d1: _id of the already created user

        Post
        .findOne({ _id: '5587f5556e6f2b38244d02d1' })
        .populate('created_by')
        .exec(function (err, story) {
          if (err) return handleError(err);
          console.log('The creator is %s', story);
          // prints "The creator is Aaron"
        });

      

The result I got is below. It gives numm a reference to created_by instead of specifying that id's username and password.

The creator is { _id: 5587f5556e6f2b38244d02d1,
  text: 'farheen123',
  created_by: null,
  __v: 0,
  created_at: Mon Jun 22 2015 17:15:25 GMT+0530 (IST) }

      

+3


source to share


1 answer


When you instantiate the Post model, you need to assign _id

to the user as ObjectId

, not a string:



var ObjectId = require('mongoose').Types.ObjectId; 
Post.create({
    text: 'farheen123',
    created_by: new ObjectId('5587bb520462367a17f242d2')
}, function(err, post) {
   if(err) console.log("Farheen has got error"+err);
   else console.log(post);
});

      

+2


source







All Articles