About mongoose connectivity - line field

I have two circuits

1 - User

UserSchema = new db.Schema({
    email:  {type: String, required: true},
    pass:   {type: String, required: true},
    nick:   {type: String, required: true},
    admin:  {type: String, default: ''},
    reg:    {type: Date, default: Date.now}
});

2 - Article

ArticleSchema = new db.Schema({
    title:      {type: String, required: true},
    alise:      {type: String},
    time:       {type: Date, defaults: Date.now},
    view:       {type: Number, defaults: 0},
    author:     {type: String},
    content:    {type: String},
    classes:    {type: db.Schema.Types.ObjectId, ref: 'Classes'},
    user:       {type: String, ref: 'User'}
});

I want the user-associated field UserSchema UserSchema.

my code is:

Model.findOne({}).populate('classes user').exec(function(err, res){
    if(err){
        cb(err);
    }else{
        cb(null, res);
    }
});

This does not work

message: 'Cast to ObjectId failed for value "tudou" at path "_id"'

What should I do?

+4
source share
1 answer

Obviously you are using Mongoose, aren't you? If so, you must use db.Schema.Types.ObjectIdthe user box for this ArticleSchema. So your ArticleSchema should look like this:

ArticleSchema = new db.Schema({
    title:      {type: String, required: true},
    alise:      {type: String},
    time:       {type: Date, defaults: Date.now},
    view:       {type: Number, defaults: 0},
    author:     {type: String},
    content:    {type: String},
    classes:    {type: db.Schema.Types.ObjectId, ref: 'Classes'},
    user:       {type: db.Schema.Types.ObjectId, ref: 'User'}
});



According to the documentation:

There are no unions in MongoDB, but sometimes we need links to documents in other collections. This is where the population comes.


So, by looking at here , we can do something like this:

//To create one user, one article and set the user whos created the article.
var user = new UserSchema({
    email : 'asdf@gmail.com',
    nick : 'danilo'
    ...
});
user.save(function(error) {
    var article = new ArticleSchema({
        title : 'title',
        alise : 'asdf',
        user : user,
        ...
    });
    article.save(function(error) {
        if(error) {
            console.log(error);
        }
    });
}


And find an article created for danilo:

ArticleSchema
.find(...)
.populate({
  path: 'user',
  match: { nick: 'danilo'},
  select: 'email nick -_id'
})
.exec()



mongoose populate

+2

Source: https://habr.com/ru/post/1608697/


All Articles