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

Node.js 使用Mongoose将项目推送到对象中的数组,node.js,mongodb,express,mongoose,mongoose-schema,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: { typ

我想更新数据对象中的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);
  })
但它不起作用。谢谢。

请尝试以下代码:

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


希望这能解决您的疑问

检查下面的答案。:)它没有把它推到数组中。得到
{ok:0,n:0,nModified:0}
Oops,我刚刚更新了答案。现在再试一次。当我删除所有的双QOUTE并将后者保留为{“data.posts”:post}时更新它就可以了。是的,现在可以了,谢谢。我移除了双qoutes,它仍然有效