1
我想追加一个字符串到一个数组,将用于识别多个聊天室中的用户。我已经尝试过,无法让这个工作。日志不熄什么,但:追加到数组nodejs mongodb
[]
if (req.body.method == "setid") {
if(req.locals.user.chatid == null){
req.locals.user.chatid = {};
}
app.model.User.update(
{ _id: req.locals.user._id },
{ $addToSet: { chatid: [{mid: req.body.value}]} }
);
} else if (req.body.method == "checkid" && req.body.value) {
app.model.User.find({
"chatid": req.body.value
}, function(err, FoundUser) {
if (err || !FoundUser) {
res.end("ERROR");
} else {
console.log(FoundUser);
res.end(FoundUser[0].displayName);
}
});
}
蒙戈结构
{
email: { type: String, index: { unique: true }, required: true },
password: { type: String },
changeName: {type: Boolean},
displayName: { type: String, index: { unique: true }, required: true },
avatar: { type: String, default: '/assets/anon.png' },
permissions: {
chat: { type: Boolean, default: true },
admin: { type: Boolean, default: false }
},
online: { type: Boolean, default: true },
channel: { type: Types.ObjectId, ref: 'Channel', default: null }, //users channel
banned: { type: Boolean, default: false },
banend: {type:String, default: ''},
subs: [{ type: Types.ObjectId, ref: 'User' }],
about: { type: String },
temporary: {type: Boolean, default: false},
chatid:[{mid: {type:String}}]
}
我照你说的去做了。我修改代码,如下所示: \t \t \t \t app.model.User.update( \t \t \t \t {_id:req.locals.user._id}, \t \t \t \t {$ addToSet:{chatid: {中期:req.body.value}}}, \t \t \t \t功能(ERR,结果){ \t \t \t \t \t如果(结果) \t \t \t \t \t \t console.log(result); \t \t \t \t \t} \t \t \t \t); 之后,setid正在工作。我感谢你的帮助,并发现它绝对有用。 – Justin
我修改后的代码如下: app.model.User.find({ “chatid”:{$ elemMatch:{ “_id”:req.body.value}}} 。 代码现在工作完全我很欣赏你帮助!注意:中间改为_id。 – Justin