mongoose的population数据填充关联不成功
跟着项目做数据关联不成功,然后我找了网上的demo也是不成功,很无语。
demo如下,首先创建三个model :User、Post、Comment,然后将数据插入到数据库保存,在访问服务器时候执行createServer里面的代码,populate('posts', 'title')将Post集合的title字段填充关联到User集合里的posts字段。但是打印效果是:
[ { name: 'aikin', _id: 595639aa9a73292826000001, posts: [] } ] [ { name: 'aikin', _id: 595639aa9a73292826000001, posts: [] } ]
为什么posts字段为空呢?
完整代码如下:
const http = require('http'); const mongoose = require('mongoose'); var Schema = mongoose.Schema; var ObjectId = Schema.Types.ObjectId; var UserSchema = new Schema({ name : { type: String, unique: true }, posts : [{ type: ObjectId, ref: 'Post' }] }); var User = mongoose.model('User', UserSchema); var PostSchema = new Schema({ poster : { type: ObjectId, ref: 'User' }, comments : [{ type: ObjectId, ref: 'Comment' }], title : String, content : String }); var Post = mongoose.model('Post', PostSchema); var CommentSchema = new Schema({ post : { type: ObjectId, ref: "Post" }, commenter : { type: ObjectId, ref: 'User' }, content : String }); var Comment = mongoose.model('Comment', CommentSchema); var db = mongoose.connect('mongodb://localhost/alan'); db.connection.on("error", (error) => { console.log("数据库连接失败:" + error); }); db.connection.on("open", () => { console.log("——数据库连接成功!——"); // createData(); // 插入数据 }); function createData() { var users ; var posts ; var comments ; users = { name : 'aikin', // posts : [new ObjectId] }; posts = { title : 'post-by-luajin', // poster : new ObjectId, // comments : [new ObjectId] }; comments = { content : 'comment-by-aikin', // commenter : new ObjectId, // post : new ObjectId }; var _user = new User(users); var _post = new Post(posts); var _comment = new Comment(comments); _user.save((err, user) => { if (err) console.log(err); console.log(user); }); _post.save((err, post) => { if (err) console.log(err); console.log(post); }); _comment.save((err, comment) => { if (err) console.log(err); console.log(comment); }); } http.createServer((req, res) => { res.writeHead(200,{"Content-Type": "text/plain"}); /*CN.findOne({name: 'Alan'}, (err, data) => { console.log(data); });*/ User.find() .populate('posts', 'title') .exec(function(err, docs) { console.log(docs); // post-by-aikin res.write("hello"); res.end(); }); }).listen(4000,() => { console.log("Server run at port", 4000); });
补充一下,由于我的系统是win7 32位但目前的mongodb都不支持32位的,所以我装了个2012年的mongodb 2.0.4版本,和同时间段的mongoose 2.6.0版本