【问题标题】:push items to an array in a object using Mongoose使用 Mongoose 将项目推送到对象中的数组
【发布时间】:2019-01-06 19:50:53
【问题描述】:

我想更新数据对象中的帖子数组。 它在这里工作的是我的架构:

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);
  })

但它不起作用。谢谢。

【问题讨论】:

  • 检查下面的答案。 :)

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


【解决方案1】:

试试这个代码:

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

Read more about $push here.

希望这能解决您的问题!

【讨论】:

  • 它没有将它推送到数组中。收到{ok:0, n:0, nModified:0}
  • 糟糕,我刚刚更新了答案。现在再试一次。
  • 当我删除所有双引号并将后者保留为 { "data.posts": post } 时更新它可以工作
  • 是的,现在可以了,谢谢。我删除了双引号,它仍然有效
猜你喜欢
  • 2019-04-08
  • 1970-01-01
  • 2020-04-02
相关资源
最近更新 更多