我有一个叫做people的mongodb集合 其架构如下:

people: {
         name: String, 
         friends: [{firstName: String, lastName: String}]
        }

现在,我有一个非常基本的快速应用程序连接到数据库,并成功地创建“人”与一个空的朋友数组。

在应用程序的次要位置,有一个添加好友的表单。表单接收firstName和lastName,然后是带有名称字段的POSTs,同样用于引用适当的people对象。

我有一个困难的时间做的是创建一个新的朋友对象,然后“推”到朋友数组。

我知道当我通过mongo控制台这样做时,我使用$push作为查找标准后的第二个参数的更新函数,但我似乎找不到合适的方法让猫鼬这样做。

db.people.update({name: "John"}, {$push: {friends: {firstName: "Harry", lastName: "Potter"}}});

当前回答

推到嵌套字段-使用点符号

对于任何想知道如何推到嵌套字段时,例如这个Schema。

const UserModel = new mongoose.schema({
  friends: {
    bestFriends: [{ firstName: String, lastName: String }],
    otherFriends: [{ firstName: String, lastName: String }]
  }
});

你只需使用点符号,像这样:

const updatedUser = await UserModel.update({_id: args._id}, {
  $push: {
    "friends.bestFriends": {firstName: "Ima", lastName: "Weiner"}
  }
});

其他回答

这就是你如何推送一个项目——官方文档

const schema = Schema({ nums: [Number] });
const Model = mongoose.model('Test', schema);

const doc = await Model.create({ nums: [3, 4] });
doc.nums.push(5); // Add 5 to the end of the array
await doc.save();

// You can also pass an object with `$each` as the
// first parameter to use MongoDB's `$position`
doc.nums.push({
  $each: [1, 2],
  $position: 0
});
doc.nums;

使用$push更新文档并在数组中插入新值。

发现:

db.getCollection('noti').find({})

查找结果:

{
    "_id" : ObjectId("5bc061f05a4c0511a9252e88"),
    "count" : 1.0,
    "color" : "green",
    "icon" : "circle",
    "graph" : [ 
        {
            "date" : ISODate("2018-10-24T08:55:13.331Z"),
            "count" : 2.0
        }
    ],
    "name" : "online visitor",
    "read" : false,
    "date" : ISODate("2018-10-12T08:57:20.853Z"),
    "__v" : 0.0
}

更新:

db.getCollection('noti').findOneAndUpdate(
   { _id: ObjectId("5bc061f05a4c0511a9252e88") }, 
   { $push: { 
             graph: {
               "date" : ISODate("2018-10-24T08:55:13.331Z"),
               "count" : 3.0
               }  
           } 
   })

更新结果:

{
    "_id" : ObjectId("5bc061f05a4c0511a9252e88"),
    "count" : 1.0,
    "color" : "green",
    "icon" : "circle",
    "graph" : [ 
        {
            "date" : ISODate("2018-10-24T08:55:13.331Z"),
            "count" : 2.0
        }, 
        {
            "date" : ISODate("2018-10-24T08:55:13.331Z"),
            "count" : 3.0
        }
    ],
    "name" : "online visitor",
    "read" : false,
    "date" : ISODate("2018-10-12T08:57:20.853Z"),
    "__v" : 0.0
}

推到嵌套字段-使用点符号

对于任何想知道如何推到嵌套字段时,例如这个Schema。

const UserModel = new mongoose.schema({
  friends: {
    bestFriends: [{ firstName: String, lastName: String }],
    otherFriends: [{ firstName: String, lastName: String }]
  }
});

你只需使用点符号,像这样:

const updatedUser = await UserModel.update({_id: args._id}, {
  $push: {
    "friends.bestFriends": {firstName: "Ima", lastName: "Weiner"}
  }
});

要做到这一点,一个简单的方法是使用以下方法:

var John = people.findOne({name: "John"});
John.friends.push({firstName: "Harry", lastName: "Potter"});
John.save();

//这是我对这个问题的解决方案。

//我想在worKingHours(对象数组)中添加新对象——>

workingHours: [
  {
    workingDate: Date,
    entryTime: Date,
    exitTime: Date,
  },
],

/ / employeeRoutes.js

const express = require("express");
const router = express.Router();
const EmployeeController = require("../controllers/employeeController");



router
  .route("/:id")
  .put(EmployeeController.updateWorkingDay)

/ / employeeModel.js

const mongoose = require("mongoose");
const validator = require("validator");

const employeeSchema = new mongoose.Schema(
  {
    name: {
      type: String,
      required: [true, "Please enter your name"],
    },
    address: {
      type: String,
      required: [true, "Please enter your name"],
    },
    email: {
      type: String,
      unique: true,
      lowercase: true,
      required: [true, "Please enter your name"],
      validate: [validator.isEmail, "Please provide a valid email"],
    },
    phone: {
      type: String,
      required: [true, "Please enter your name"],
    },
    joiningDate: {
      type: Date,
      required: [true, "Please Enter your joining date"],
    },
    workingHours: [
      {
        workingDate: Date,
        entryTime: Date,
        exitTime: Date,
      },
    ],
  },
  {
    toJSON: { virtuals: true },
    toObject: { virtuals: true },
  }
);

const Employee = mongoose.model("Employee", employeeSchema);

module.exports = Employee;

/ / employeeContoller.js

/////////////////////////// 下面的解决方案是 ///////////////////////////////

//这是用来增加一天、进入和退出时间的

exports.updateWorkingDay = async (req, res) => {
  const doc = await Employee.findByIdAndUpdate(req.params.id, {
    $push: {
      workingHours: req.body,
    },
  });
  res.status(200).json({
    status: "true",
    data: { doc },
  });
};

https://www.youtube.com/watch?v=gtUPPO8Re98