This question already has answers here:
Mongoose Unique values in nested array of objects
(2个答案)
已关闭6年。
给定 Mongoose 模式
从我的代码中,我想将对象推送到
(2个答案)
已关闭6年。
给定 Mongoose 模式
var SomeSchema = new Schema({
// ...
members: [
{
name: String,
username: String
}
]
});
从我的代码中,我想将对象推送到
members
,但前提是数组中没有给定的用户名。我怎么用 Mongoose 呢? 最佳答案
您可以在更新查询的条件部分中检查用户名:
var conditions = {
_id: id,
'members.username': { $ne: 'something' }
};
var update = {
$addToSet: { members: { name: 'something', username: 'something' } }
}
SomeModel.findOneAndUpdate(conditions, update, function(err, doc) {
...
});
关于node.js - 如果键不存在,则将值插入数组,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/26328891/
10-12 15:31