我创建了2个这样的模式
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);
然后我想找到具有链接的用户对象google.com
User.find({'links.url': 'http://google.com' },function(err, foundLinks){
console.log(foundLinks);
});
但是返回了空列表
[]
有人可以建议我如何解决它?
这是完整的源代码:
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);
});
});
});
非常感谢。
PS。抱歉我的英语不好。
答案 0 :(得分:0)
现在,我首先查询链接ID,然后通过链接ID查找用户。