Node.js 如何更新包含mongoose中对象数组的模型
我想知道如何用猫鼬更新喜欢的数组:Node.js 如何更新包含mongoose中对象数组的模型,node.js,mongodb,express,mongoose,Node.js,Mongodb,Express,Mongoose,我想知道如何用猫鼬更新喜欢的数组: var postSchema = new mongoose.Schema({ author: String, content: String, date: String, likes: [{theID: String}], numDate: Number }); var UserSchema = mongoose.Schema({ username: { type: String },
var postSchema = new mongoose.Schema({
author: String,
content: String,
date: String,
likes: [{theID: String}],
numDate: Number
});
var UserSchema = mongoose.Schema({
username: {
type: String
},
password: {
type: String
},
email: {
type: String
},
first: {
type: String
},
posts: [postSchema],
last: {
type: String
},
followers: [{theID: String}],
following: [{theID: String}],
img: { data: Buffer, contentType: String },
admin: {type: Boolean, default: false}
});
我可以通过
这样做:
User.update({_id: req.user.id}, {
$push: {"posts": {_id : req.body.theData}}
}, function(err, user){
res.redirect('profile');
});
有没有类似的方法,我可以查看一个特定的用户,然后查看该用户拥有的特定帖子,然后更新它,将字符串推送到likes数组中?首先,您需要选择要更新like-like的帖子,您可以借助_idof post
{u id:req.user.id,_id:posts.\u id}
然后你需要更新like数组,可以这样做{$push:{“posts.$.likes”:req.user.anotherUserId}}//anotherUserId是喜欢它的用户的id。
同样的方法,如果用户不喜欢post,你可以拉取用户id从数组中删除id
User.update({_id: req.user.id,_id:posts._id}, {
$push: {"posts.$.likes": req.user.id}
}, function(err, user){
});