简体   繁体   English

如何使用 Mongoose 将数据推送到 MongoDB 中的嵌套数组

[英]How to push data with Mongoose to a nested array in MongoDB

I'm trying to push data to a nested array in mongodb.我正在尝试将数据推送到 mongodb 中的嵌套数组。 I'm using mongoose as well.我也在使用猫鼬。

This is just mock code to see if i can get it working:这只是模拟代码,看看我是否可以让它工作:

User model:用户模型:

import mongoose from "mongoose";

const CoinSchema = new mongoose.Schema({
  coinID: { type: String },
});
const CoinsSchema = new mongoose.Schema({
  coin: [CoinSchema],
});

const WatchlistSchema = new mongoose.Schema({
  watchlistName: { type: String },
  coins: [CoinsSchema],
});

const NameSchema = new mongoose.Schema({
  firstName: { type: String },
  lastName: { type: String },
  username: { type: String },
});

const UserSchema = new mongoose.Schema({
  name: [NameSchema],
  watchlists: [WatchlistSchema],
  test: String,
});

const User = mongoose.model("User", UserSchema);

export default User;

route:路线:

fastify.put("/:id", async (request, reply) => {
    try {
      const { id } = request.params;
      const newCoin = request.body;
      const updatedUser = await User.findByIdAndUpdate(id, {
        $push: { "watchlists[0].coins[0].coin": newCoin },
      });
      await updatedUser.save();
      // console.dir(updatedUser, { depth: null });
      reply.status(201).send(updatedUser);
    } catch (error) {
      reply.status(500).send("could not add to list");
    }
  });

request.body // "coinID": "test" request.body // "coinID": "test"

I've tried a lot of different ways to push this data but still no luck.我尝试了很多不同的方法来推送这些数据,但仍然没有运气。 I still get 201 status codes in my terminal which indicates something has been pushed to the DB, but when I check nothing new is there.我仍然在我的终端中收到 201 状态代码,这表明某些内容已被推送到数据库,但是当我检查没有任何新内容时。

Whats the correct way to target nested arrays and push data to them?定位嵌套数组并将数据推送给它们的正确方法是什么?

It's not perfect but you could get the user document, update the user's watchlist, and then save the updated watchlist like so:这并不完美,但您可以获取用户文档,更新用户的监视列表,然后像这样保存更新的监视列表:

fastify.put("/:id", async (request, reply) => {
    try {
        const { id } = request.params;
        const newCoin = request.body;
        
        // get the user
        let user = await User.findById(id);

        // push the new coin to the User's watchlist
        user.watchlists[0].coins[0].coin.push(newCoin);

        //update the user document
        const updatedUser = await User.findOneAndUpdate({ _id: id },
            {
                watchlists: user.watchlists,
            }, 
            { 
                new: true, 
                useFindAndModify: false 
            }
        );
        
        reply.status(201).send(updatedUser);
    } catch (error) {
        reply.status(500).send("could not add to list");
    }
  });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM