通过猫鼬将项目推入mongo数组

基本上我有一个mongodb集合叫做'people'

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

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

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

我很难做到的是创建一个新的朋友对象,然后“推送”;它进入朋友数组。

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

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

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

你有两个选择:

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

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

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

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

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

推动美元操作符将指定的值附加到数组。

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

推动美元将数组字段的值作为元素添加。

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

var objFriends = { fname:"fname",lname:"lname",surname:"surname" };
Friend.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);

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

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

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

就我而言,我是这样做的

  const eventId = event.id;
User.findByIdAndUpdate(id, { $push: { createdEvents: eventId } }).exec();

首先,我尝试了这个代码

const peopleSchema = new mongoose.Schema({
name: String,
friends: [
{
firstName: String,
lastName: String,
},
],
});
const People = mongoose.model("person", peopleSchema);
const first = new Note({
name: "Yash Salvi",
notes: [
{
firstName: "Johnny",
lastName: "Johnson",
},
],
});
first.save();
const friendNew = {
firstName: "Alice",
lastName: "Parker",
};
People.findOneAndUpdate(
{ name: "Yash Salvi" },
{ $push: { friends: friendNew } },
function (error, success) {
if (error) {
console.log(error);
} else {
console.log(success);
}
}
);
但是我注意到只有第一个朋友(即johny Johnson)得到保存和目标推数组元素在现有的数组"朋友"当我运行代码时,似乎不工作,在数据库中只显示“第一个朋友”;和“;friends"数组只有一个元素! 所以简单的解决方案写在

const peopleSchema = new mongoose.Schema({
name: String,
friends: [
{
firstName: String,
lastName: String,
},
],
});
const People = mongoose.model("person", peopleSchema);
const first = new Note({
name: "Yash Salvi",
notes: [
{
firstName: "Johnny",
lastName: "Johnson",
},
],
});
first.save();
const friendNew = {
firstName: "Alice",
lastName: "Parker",
};
People.findOneAndUpdate(
{ name: "Yash Salvi" },
{ $push: { friends: friendNew } },
{ upsert: true }
);

添加“{upsert: true}”;在我的情况下解决了问题,一旦代码被保存,我运行它,我看到"朋友"数组现在有2个元素! 如果对象不存在,upsert = true选项将创建该对象。默认设置为false。

如果它不工作,使用下面的片段

People.findOneAndUpdate(
{ name: "Yash Salvi" },
{ $push: { friends: friendNew } },
).exec();

使用Mongoose将项推入数组的另一种方法是- addToSet美元,如果你只想将唯一的项推入数组。推动美元操作符只是将对象添加到数组中,无论该对象是否已经存在,而addToSet美元仅在对象不存在于数组中时这样做,以不包含重复。

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

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

引用:

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

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;

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

对于任何想知道如何推动 嵌套的领域当你有例如这个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"}
}
});

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

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