【发布时间】:2020-12-04 12:26:14
【问题描述】:
我正在尝试使用在前端(网站 ui)中创建的字符串在 mongo 数据库中附加一个空数组,相关代码片段如下:
猫鼬模式
email: String,
displayName: String,
googleId: String,
toIgnore: [{toIgnoreURL: String}]
})
使用护照和护照-google-oauth20 创建文档
User.findOne({email: email.emails[0].value}).then((currentUser)=>{
if(currentUser){
// user does already exist
console.log('welcome back!', currentUser)
done(null, currentUser)
}
else{ // user doesn't exist yet
new User({
email: email.emails[0].value,
displayName: email.displayName,
googleId: email.id,
toIgnore: []
}).save().then((newUser)=>{
console.log('new user created: ' + newUser)
done(null, newUser)
});
}
})
最后尝试附加“用户”集合(当前登录用户的)的 toIgnore 数组属性
User.update(
{email: emailThisSession},
{$push: {toIgnore: {toIgnoreURL: url}}})
在mongodb中我看到下面的文档创建成功了
_id
:ObjectId(
IdOfDocumentInMongoDB)
toIgnore
:
Array
email
:
"myactualtestemail"
googleId
:
"longgoogleidonlynumbers"
__v
:
0
(也见附图) document in mongodb ui
我似乎不知道如何实际填充“toIgnore”数组。 例如,当控制台记录以下内容时
var ignoreList = User.findOne({email:emailThisSession}).toIgnore;
console.log(ignoreList)
输出为undefined
请注意,控制台记录 url 变量确实会打印我想要附加到数组的值!
我尝试了在模式构建器和文档创建中我能想到的任何格式组合,但我找不到正确的方法来完成它!
任何帮助将不胜感激!
更新,使用 promise 也不起作用
User.findOne({email:emailThisSession}).then((currentUser)=>{ //adding .exec() after findOne({query}) does not help as in User.findOne({email:emailThisSession}).exec().then(...)
console.log(currentUser.toIgnore, url) //output is empty array and proper value for url variable, empty array meaning []
currentUser.toIgnore.push(url)
});
同时调整Schema如下:
const userSchema = new Schema({
email: String,
displayName: String,
googleId: String,
toIgnore: []
})
解决方案
我只需要将更新命令更改为
User.updateOne(
{email: emailThisSession},
{$push: {toIgnore: {toIgnoreURL: url}}}).then((user)=>{
console.log(user)
})
谢谢@yaya!
【问题讨论】:
标签: node.js arrays mongodb mongoose passport.js