You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Mongoose中向文档对象内的数组执行$push操作?

How to $push to a Nested Array in Mongoose

Got it, let's fix that $push issue you're hitting. The problem with your current approach is that you're wrapping the $push inside the rating object, which tells Mongoose you want to overwrite the entire rating field instead of modifying its nested usersRated array.

Here's the correct way to target that nested array:

1. Using Direct Update with $push

You need to use a dot-separated path to point directly to the usersRated array inside the rating object. Here's how it looks in practice:

// Using updateOne (callback style)
YourModel.updateOne(
  { _id: yourDocumentId }, // Your query to find the target document
  { $push: { "rating.usersRated": data.userId } }, // The correct update operation
  (err, updateResult) => {
    if (err) {
      console.error("Failed to push userId:", err);
    } else {
      console.log("Successfully added userId to usersRated:", updateResult);
    }
  }
);

// Or with async/await (cleaner for modern code)
try {
  const updateResult = await YourModel.updateOne(
    { _id: yourDocumentId },
    { $push: { "rating.usersRated": data.userId } }
  );
  console.log("Successfully added userId:", updateResult);
} catch (err) {
  console.error("Error pushing userId:", err);
}

2. Alternative: Fetch the Document First, Modify, Then Save

If you prefer working with the document instance directly (useful if you need to run additional logic on the document), you can do this:

try {
  const doc = await YourModel.findById(yourDocumentId);
  doc.rating.usersRated.push(data.userId); // Push directly to the nested array
  await doc.save(); // Save changes back to the database
  console.log("UserId added successfully!");
} catch (err) {
  console.error("Error updating document:", err);
}

Quick Note on Schema Best Practices

To avoid unexpected issues later, it's a good idea to explicitly define the type for your usersRated array (especially if it's storing user ObjectIds):

const yourSchema = new mongoose.Schema({
  rating: {
    usersRated: [{ type: mongoose.Schema.Types.ObjectId, ref: "User" }], // Specify type for user IDs
    rating: { type: Number, default: 0 } // Add a default value if needed
  }
});

That should get your $push working as expected!

内容的提问来源于stack exchange,提问作者Michael Kutateladze

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 08:31:48