gpt4 book ai didi

node.js - 防止 Mongoose 模式中数组中的重复条目

转载 作者:IT老高 更新时间:2023-10-28 13:37:53 27 4
gpt4 key购买 nike

用户架构:

var UserSchema = new Schema({

name: { type: String, required:true },
email: { type: String, required:true, lowercase: true , index : { unique: true } },
password : { type: String, required:true , select:true },
blog_bookmarks: [{ type: String }]

});

为特定用户向 blog_bookmarks 添加值的 API

api.post('/add_bookmark_blog', function(req, res){

User.findOne({_id: req.query.user_id}, function(err, user){
if(err)
{
res.json(err)
}
else{
var blogid = req.body.blog_id;
user.find({ blog_bookmarks : blogid}, function(res1, result){
if(res1){
user.blog_bookmarks.push(blogid);
user.save(function(err) {
if(err){
res.json('ERROR at adding bookmark')
}
else {
res.json('bookmark for blog added')
}
})
}
else{
res.json('Already bookmarked')
}
});
}
})
});

我只想将 blog_id 添加到 blog_bookmarks 数组中,前提是它不存在,我不想要多个条目。

目前,user.find() 给出控制台错误

user.find() is not a function

如何实现?

最佳答案

为避免 blog_bookmarks 中出现重复值,请使用 $addToSet运算符(operator)。

User.update({_id: req.query.user_id}, {$addToSet: {blog_bookmarks: blogid}})

您的 user.find() 可能会给您一个错误,因为它应该是 User.find() 以大写 U 开头。

关于node.js - 防止 Mongoose 模式中数组中的重复条目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38165736/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com