0

I have created 2 schemas like this

var LinkSchema = new mongoose.Schema({
    url: String,
    name: String
});
var Link = mongoose.model('Link', LinkSchema);

var UserSchema = new mongoose.Schema({
    name: String,
    links: [LinkSchema]
});
var User = mongoose.model('User', UserSchema);

Then I would like to find the user object that has link too google.com

User.find({'links.url': 'http://google.com' },function(err, foundLinks){
    console.log(foundLinks);
});

but the empty list was returned

[]

Could anyone suggest me how can I solve it?

Here is full source code:

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

mongoose.connect('mongodb://localhost/test');

var LinkSchema = new mongoose.Schema({
    url: String,
    name: String
});
var Link = mongoose.model('Link', LinkSchema);

var UserSchema = new mongoose.Schema({
    name: String,
    links: [LinkSchema]
});
var User = mongoose.model('User', UserSchema);

var link = new Link();
link.url = "http://google.com";
link.name = "Google";
link.save(function(err,link){
    //console.log(link);
    var user = new User();
    user.name = "Varavut";
    user.links.push(link._id);
    user.save(function(err,user){
        //console.log(user);
        User.find({'links.url': 'http://google.com' },function(err, foundLinks){
               console.log(foundLinks);
           });
    });
});

Thank you very much.

ps. Sorry for my bad English.

  • You seem to be trying to combine linking _and_ embedding, but you need to go one way or the other. See http://stackoverflow.com/questions/5373198/mongodb-relationships-embed-or-reference – JohnnyHK Feb 03 '15 at 14:40
  • Sorry in the title I meant [Sub Docs](http://mongoosejs.com/docs/subdocs.html) of Mongoose. I can't got with the embedded documents because in the real application both schema are can created independently and many User objects can refer to the same link object. – Varavut Lormongkol Feb 03 '15 at 15:23
  • You cannot query populated documents before they are populated. You will need to perform a regular (empty) find query with .populate() and filter your results when the query is done. – Thomas Bormans Feb 03 '15 at 15:36
  • Thank you very much. Now, I go with query an id of link first then find for the user by an id of link. – Varavut Lormongkol Feb 04 '15 at 00:11

1 Answers1

0

Now, I go with query an id of link first then find for the user by an id of link.