使用Mongoose将项目推送到对象中的数组

时间:2018-07-30 14:17:11

标签: node.js mongodb express mongoose mongoose-schema

我想更新数据对象中的posts数组。 这是我的计划,很重要:

const mongoose = require('mongoose');
const Post = require('./post');
const Review = require('./comment')

    const User = mongoose.Schema({
        _id: mongoose.Schema.Types.ObjectId,

        username: {
            type: String,
            required: true
        }

        // necessary details needed for the user to initially working with
        data: {

            posts: [
                Post
            ],
            following: [String]
            }
        }

    });

我已经尝试过:

User.update({_id: user}, {data:{$push: {posts: post
  }}}).then(data=>{
    console.log(data);
  })

但是它确实起作用。谢谢。

1 个答案:

答案 0 :(得分:0)

尝试以下代码:

User.update(
    { "_id": user },
    {
        "$push":
            {
                "data.posts": post
            }
    }
).then(data => {
    console.log(data);
})

Read more about $push here.

希望这可以解决您的查询!