Javascript 使用mongodb中的mongoose更新对象中的字段
我在mongodb有一个简单的收藏。 我用猫鼬 我有一个带有一个字段类型对象的用户模型。 我想动态地改变这个对象。但这段代码不起作用,我使用了Javascript 使用mongodb中的mongoose更新对象中的字段,javascript,mongodb,mongoose,Javascript,Mongodb,Mongoose,我在mongodb有一个简单的收藏。 我用猫鼬 我有一个带有一个字段类型对象的用户模型。 我想动态地改变这个对象。但这段代码不起作用,我使用了findbyiandupdate(),findById,findOne(),findOneAndUpdate() 我认为,要解决此问题,您需要在模式中添加更多字段: 我用这些数据创建了一个示例: const UsersSchema = new mongoose.Schema({ likes :[ { thema:{
findbyiandupdate()
,findById
,findOne()
,findOneAndUpdate()
我认为,要解决此问题,您需要在模式中添加更多字段: 我用这些数据创建了一个示例:
const UsersSchema = new mongoose.Schema({
likes :[
{
thema:{
type: String
},
likes_amount:{
type: Number
},
_id:false
}]
});
module.exports = mongoose.model('Users', UsersSchema);
我添加了一个用户:
var newUser = new UserModel({
likes:[{
thema:'foo',
likes_amount:1
}]
});
newUser.save();
下面是增加每个主题的喜欢度的代码:
const thems = ['foo', 'bar'];
const userId = "5b4d0b1a1ce6ac3153850b6a";
UserModel.findOne({_id:userId})
.then((result) => {
var userThemas = result.likes.map(item => {
return item.thema;
});
for (var i = 0; i < thems.length; i++) {
//if exists it will increment 1 like
if (userThemas.includes(thems[i])) {
UserModel.update({_id: result._id, "likes.thema" : thems[i]}, {$inc: {"likes.$.likes_amount": 1}})
.then((result) => {
console.log(result);
}).catch((err) => {
console.log(err)
});
} else {
//if doesn't exist it will create a thema with 1 like
UserModel.update({_id: result._id},
{
$addToSet: {
likes: {
$each: [{thema: thems[i], likes_amount: 1}]
}
}})
.then((result) => {
console.log(result);
}).catch((err) => {
console.log(err)
});
}
}
}).catch((err) => {
console.log(err)
});
const thems=['foo','bar'];
const userId=“5b4d0b1a1ce6ac3153850b6a”;
findOne({u id:userId})
。然后((结果)=>{
var userThemas=result.likes.map(项=>{
返回item.thema;
});
对于(var i=0;i{
控制台日志(结果);
}).catch((错误)=>{
console.log(错误)
});
}否则{
//如果不存在,它将创建一个带有1个类似项的主题
update({u id:result.\u id},
{
$addToSet:{
喜欢:{
$each:[{thema:thems[i],金额:1}]
}
}})
。然后((结果)=>{
控制台日志(结果);
}).catch((错误)=>{
console.log(错误)
});
}
}
}).catch((错误)=>{
console.log(错误)
});
此增量的数据库结果:
我希望它能对您有所帮助。您能更准确地解释一下您想做什么吗?您的IDI是什么?它是您的完整猫鼬模式吗?是的,它是complete@Aaron是否要存储主题以及每个主题的链接数量?
const thems = ['foo', 'bar'];
const userId = "5b4d0b1a1ce6ac3153850b6a";
UserModel.findOne({_id:userId})
.then((result) => {
var userThemas = result.likes.map(item => {
return item.thema;
});
for (var i = 0; i < thems.length; i++) {
//if exists it will increment 1 like
if (userThemas.includes(thems[i])) {
UserModel.update({_id: result._id, "likes.thema" : thems[i]}, {$inc: {"likes.$.likes_amount": 1}})
.then((result) => {
console.log(result);
}).catch((err) => {
console.log(err)
});
} else {
//if doesn't exist it will create a thema with 1 like
UserModel.update({_id: result._id},
{
$addToSet: {
likes: {
$each: [{thema: thems[i], likes_amount: 1}]
}
}})
.then((result) => {
console.log(result);
}).catch((err) => {
console.log(err)
});
}
}
}).catch((err) => {
console.log(err)
});