Mongoose


Update Documentation

Ways to update mongoose


Mongoose Scheme

A group have many members(ref), many expenses paid by one member(ref)

var groupSchema = new Schema(
	{
		groupName: { type: String, required: true },
		members: [
			{
				memberId: {
					type: mongoose.Schema.Types.ObjectId,
					ref: 'user',
				},
				accepted: { type: Boolean, required: true }
			},
		],
		expenses: [
			{
				description: { type: String, required: true },
				amount: { type: Number, require: true },
				payer_id: {
					type: mongoose.Schema.Types.ObjectId,
					ref: 'user',
					require: true,
				},
			},
		],
	}
);

Find doc if specific item exists in array

$elemMatch

// Get all group where member contains userId
// groupName: 1 means return `groupName` field
group.find(
		{ members: { $elemMatch: { memberId: someUserId } } }, // only if members contains userId
		{ groupName: 1, members: { $elemMatch: { memberId: someUserId } } }, // projections: groupName, specific user
		(error, groups) => {}
	);

When there is only 1 attribute filter, you can rewrite

{ members: { $elemMatch: { memberId: someUserId } } }

to

{ 'members.memberId': userId }

Update item in array

$ update operator

// set a user as accepted
group.findOneAndUpdate(
		{ _id: groupId, 'members.memberId': userId },
		{ $set: { 'members.$.accepted': true } },
		(error, updated) => {}
	);

Push item in array

// add new expense happens in the group
group.updateOne(
		{ _id: group_id },
		{ $push: { expenses: newExpenseObj } },
		(err, res) => {}
	);

Remove item from array

// delete member from group
group.updateOne(
		{ _id: groupId },
		{ $pull: { members: { memberId: userId } } },
		(err, res) => {}
	);

Populate Ref

populate documentation

// find all expense with payer name populated within group
group.findOne(
	{ _id: groupId }, 
	(error, group) => {}
	)
	.populate('expenses.payer_id', 'name'); // use XXX.XXX to populate down level, `name` is like projection
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值