【发布时间】:2014-09-03 11:16:57
【问题描述】:
//MONGOOSE SCHEMA OBJECT
var userSchema = new Schema( {
username: { type: String, required: true, unique: true },
email: { type: String, required: true, unique: true },
tags:[ {name : String, color : String } ],
bookmarks:[{link : String, tags:[ {name : String, color : String } ]}]
} );
module.exports = userSchema; //Export the userSchema
var UserModel = mongoose.model('UserModel', userSchema ); //Create Model
module.exports = UserModel; //Export the Model
//我可以从书签数组中删除一个项目没有问题使用
UserModel.findByIdAndUpdate(userId ,{$push : {bookmarks: {link : req.body.link, tags : req.body.tags}}}, function(err, user_data) {
问题!! 如何在给定用户 _id、书签 _id 和标签 _id 或名称的书签数组中从标签数组中删除标签?
//我尝试了以下变体但没有成功
var update = {bookmarks:[{ _id : bookmarkId},
$pull: {tags:[_id : tagid ] }] };
UserModel.findByIdAndUpdate(userId ,update, function(err, user_data) {
AND
UserModel.findOne( {_id : userId}).select({ bookmarks:[ { $elemMatch: {_id : req.params.bookmarkId}}] }).exec(function(err, user_data)
最初我使用不同的模型和子文档。
var bookmarkSchema = new Schema( {
link : String,
tags:[tagSchema]
});
var tagSchema = new Schema( {
name : String,
color : String
});
var userSchema = new Schema( {
username: { type: String, required: true, unique: true },
email: { type: String, required: true, unique: true },
tags:[ {name : String, color : String } ],
bookmarks: [bookmarkSchema]
} );
但是,我无法使用上面使用的 $pull 命令从子文档中删除项目。所以我恢复到只使用一个模式/模型。 能够完成这是一项非常重要的任务,我将不胜感激。
感谢 Muhammad,但我无法让这两种方法中的任何一种起作用: 1) DB 没有任何反应,回调的值为: *受影响人数:0 *raw: {"updatedExisting":false,"n":0,"connectionId":322,"err":null,"ok":1}
UserModel.update({bookmarks:req.params.bookmarkId},
{ $pull: {"bookmarks.tags" :{_id:req.body._id, name :req.body.name ,color:req.body.color}}}, function(err, numberAffected, raw) {
2) 我必须使用lea() 函数将Mongoose 文档数据格式转换为普通的JSON。否则bookmarks.push({link:user.bookmarks[i].link,_id:user.bookmarks[i]._id,tags:tags})
不能正确结合:
bookmarks.push(user.bookmarks[i]);
在书签上[]
但是,使用lea() 函数意味着我无法使用 .save 将数据保存到数据库中
UserModel.findById(userId).lean(true).exec(function(err, user) {
【问题讨论】: