mongoose populate

關係型數據庫的join特性:坑死了,原來是沒有鏈接數據庫javascript

 

var mongoose = require('mongoose')
  , Schema = mongoose.Schema;
var util = require('util');

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


var UserSchema = Schema({
  name    : String,
  followings : [{ type: Schema.Types.ObjectId, ref: 'User' }]
});

var User = mongoose.model('User', UserSchema);
// 用來插入數據
// var lily = new User({name: 'lily'})
//    ,lucy = new User({name: 'lucy'});
// lily.save(cb);

// function cb(err) {
//     if(err) throw err;
//     lucy.followings.push(lily);// line 1
//     lucy.save(); 
    
// }
// 若是不加populate,followings是id數組。
User.findOne({name:'lucy'}).populate('followings').exec(function(err, results){
	console.log(util.inspect({result: results}));
});
相關文章
相關標籤/搜索