我有一个叫做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"}}});

当前回答

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

//我想在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

其他回答

使用$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
}

我也遇到过这个问题。我的解决办法是创建一个子模式。请参见下面的模型示例。

----人物模型

const mongoose = require('mongoose');
const SingleFriend = require('./SingleFriend');
const Schema   = mongoose.Schema;

const productSchema = new Schema({
  friends    : [SingleFriend.schema]
});

module.exports = mongoose.model('Person', personSchema);

* * *重要:SingleFriend。Schema ->确保模式使用小写

——子图式

const mongoose = require('mongoose');
const Schema   = mongoose.Schema;

const SingleFriendSchema = new Schema({
  Name: String
});

module.exports = mongoose.model('SingleFriend', SingleFriendSchema);

另一种使用Mongoose将项目推入数组的方法是- $addToSet,如果你只想将唯一的项目推入数组。$push操作符只是简单地将对象添加到数组中,无论该对象是否已经存在,而$addToSet仅在对象不存在于数组中时才这样做,以免合并重复。

PersonModel.update(
  { _id: person._id }, 
  { $addToSet: { friends: friend } }
);

这将查找您要添加到数组中的对象。如果发现,则不执行任何操作。如果不是,则将其添加到数组中。

引用:

$addToSet MongooseArray.prototype.addToSet()

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

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;

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

//我想在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