簡體   English   中英

如何使用 Mongoose 將數據推送到 MongoDB 中的嵌套數組

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

我正在嘗試將數據推送到 mongodb 中的嵌套數組。 我也在使用貓鼬。

這只是模擬代碼,看看我是否可以讓它工作:

用戶模型:

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;

路線:

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"

我嘗試了很多不同的方法來推送這些數據,但仍然沒有運氣。 我仍然在我的終端中收到 201 狀態代碼,這表明某些內容已被推送到數據庫,但是當我檢查沒有任何新內容時。

定位嵌套數組並將數據推送給它們的正確方法是什么?

這並不完美,但您可以獲取用戶文檔,更新用戶的監視列表,然后像這樣保存更新的監視列表:

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