【问题标题】:Using Mongoose $push into Array Schema type使用 Mongoose $push 进入 Array Schema 类型
【发布时间】:2018-11-09 09:20:01
【问题描述】:

我有以下用户和帖子架构,其中用户具有以下数据类型:

postCreated:{
    type: Array,
    default: []
}

Posts 的服务器路由是:

server.post('/posts',(req,res,next) => {
    const {username,title,categories,content} = req.body;
    const post = new Posts({
        username,
        title,
        categories,
        content
    });
    post.save().then((doc) => {
        console.log(doc);
        res.send(doc);
        User.findOneAndUpdate({username}, {$push: {'postCreated': doc}});
    })
    .catch((e) => {
        return next(new errors.BadRequestError(e.message));
    });
});

这会将新创建的帖子保存到数据库中并更新用户架构中的“postCreated”属性。但是,我当前的代码不起作用,有什么方法可以将新创建​​的帖子推送到“帖子创建”数组中?

感谢您的帮助。

【问题讨论】:

    标签: node.js mongoose restify


    【解决方案1】:

    看看这是否适合你:

    server.post('/posts',(req,res,next) => {
        const {username,title,categories,content} = req.body;
        const post = new Posts({
            username,
            title,
            categories,
            content
        });
        return post.save()
          .then(doc => User.findOneAndUpdate({username}, {$push: {'postCreated': doc}})
            .then(() => res.send(doc)))
        .catch(e => {
            return next(new errors.BadRequestError(e.message));
        });
    });
    

    您知道post.saveUser.findOneAndUpdate 的返回值丢失了。此外,您的 res.send(doc) 可能应该是您函数中的最后一件事。

    【讨论】:

      猜你喜欢
      • 2018-09-16
      • 2018-07-07
      • 2021-09-06
      • 2018-12-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-17
      • 2013-08-26
      相关资源
      最近更新 更多