我有一个叫做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

其他回答

假设,var friend = {firstName: 'Harry', lastName: 'Potter'};

你有两个选择:

更新内存中的模型,并保存(简单的javascript array.push):

person.friends.push(friend);
person.save(done);

or

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

在可能的情况下,我总是尝试选择第一个选项,因为它会尊重mongoose给你的更多好处(钩子、验证等)。

然而,如果你正在进行大量的并发写操作,你就会遇到竞态条件,你最终会出现讨厌的版本错误,阻止你每次替换整个模型,并失去你之前添加的朋友。所以只有在绝对必要的情况下才会选择后者。

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

//我想在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操作符将指定的值附加到数组中。

{ $push: { <field1>: <value1>, ... } }

$push将数组字段的值添加为其元素。

上面的答案满足所有的要求,但我通过做以下工作

var objFriends = { fname:"fname",lname:"lname",surname:"surname" };
People.findOneAndUpdate(
   { _id: req.body.id }, 
   { $push: { friends: objFriends  } },
  function (error, success) {
        if (error) {
            console.log(error);
        } else {
            console.log(success);
        }
    });
)

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

----人物模型

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);

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

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