猫鼬填充数组为空

时间:2018-09-08 20:07:20

标签: javascript node.js mongodb mongoose

我在我的model.js中定义了UserSchemaPostSchemaUserSchema引用了自己的Post,而PostSchema引用了其作者。

在我的controllers.js方法中,我正在创建一个用户和一个帖子实例(绑定到新创建的用户)。我现在正在尝试填充用户的帖子,但是猫鼬返回一个空数组。但是,另一种解决方法是可行的(我可以通过Post实例来检索用户)。

  

models.js

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const UserSchema = new Schema({
    username: String,
    posts: [{
      type: Schema.Types.ObjectId,
      ref: 'Post'
    }]
  })
const PostSchema = new Schema({
    content: String,
    author: {
      type: Schema.Types.ObjectId,
      ref: 'User'
    }
  })
const Post = mongoose.model('Post', PostSchema, 'posts');
const User = mongoose.model('User', UserSchema, 'users');

module.exports = { Post, User }
  

controllers.js

require('../model/db'); // DB config
const mongoose = require('mongoose');
const models = require('../model/models');

const getUser = (req, res) => {
        const user = new models.User({
            _id: new mongoose.Types.ObjectId(),
            username: 'JohnDoe'
        });

        user.save(function (err) {
            if (err) return res.json(err);

            const post = new models.Post({
                content: 'New Post',
                author: user.id
            });
        post.save(function (err) {
            if (err) return res.json(err);
            models.User.findOne({
                    username: 'JohnDoe'
                })
                .populate('posts').exec((err, user) => {
                    res.json(user);
                })
        });
    });
}

const getPost = (req, res) => {
        const user = new models.User({
            _id: new mongoose.Types.ObjectId(),
            username: 'JohnDoe'
        });

        user.save(function (err, user) {
                if (err) return res.json(err);

                const post = new models.Post({
                    content: 'NewPost',
                    author: user.id
                });

                post.save(function (err, post) {
                    if (err) return res.json(err);
                    models.Post.findOne({
                            content: 'NewPost'
                        })
                        .populate({
                            path: 'author',
                            model: 'User'
                        }).exec((err, user) => {
                            res.json(user);
                        })
                });

            });
}
  

getUser的结果(帖子为空):

{
    "posts": [],
    "_id": "5b9426a6fd187d3949470f54",
    "username": "JohnDoe",
    "__v": 0
}
  

getPost结果(正确返回了作者)

{
    "_id": "5b94287e99072c3a173419f2",
    "content": "NewPost",
    "author": {
        "posts": [],
        "_id": "5b94287e99072c3a173419f0",
        "username": "JohnDoe",
        "__v": 0
    },
    "__v": 0
}

1 个答案:

答案 0 :(得分:1)

您需要按如下所示将帖子ID推送到用户模型中的posts数组中

const getUser = (req, res) => {
    const newUser = new models.User({ username: 'JohnDoe' });

    newUser.save(user => {
        if (err) return res.json(err);

        const newPost = new models.Post({
            content: 'New Post',
            author: user._id
        });

        newPost.save(post => {
            if (err) return res.json(err);

            models.User.findByIdAndUpdate(user._id,
                { '$push': { 'posts': post._id } },
                { 'new': true }
            )
            .populate('posts')
            .exec((err, u) => {
                res.json(u);
            })
        });
    });
}

使用异步/等待

const getUser = async (req, res) => {
    try {
        const newUser = new models.User({ username: 'JohnDoe' });
        const user = await newUser.save();

        const newPost = new models.Post({
            content: 'New Post',
            author: user._id
        });
        const post = await newPost.save();

        const result = await models.User.findByIdAndUpdate(user._id,
            { '$push': { 'posts': post._id } },
            { 'new': true }
        )
        .populate('posts')
        .exec();

        res.json(result)
    } 
    catch (err) {
        return res.json(err);  
    }
}