[英]Unable to push an item into a MongoDB array within the document while using Waterline
[英]Unable to Append Array Within MongoDB (mongoose) Document
我正在尝试 append 在 mongo 数据库中使用在前端(网站 ui)中创建的字符串的空数组,相关代码片段如下:
mongoose 架构
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)
});
}
})
最后尝试 append 'User' 集合的 toIgnore 数组属性(当前登录的用户)
User.update(
{email: emailThisSession},
{$push: {toIgnore: {toIgnoreURL: url}}})
在mongodb 看到下面的文档创建成功
_id
:ObjectId(
IdOfDocumentInMongoDB)
toIgnore
:
Array
email
:
"myactualtestemail"
googleId
:
"longgoogleidonlynumbers"
__v
:
0
(也如附图所示) mongodb ui 中的文档
我似乎不知道如何实际填充“toIgnore”数组。 例如,当控制台记录以下内容时
var ignoreList = User.findOne({email:emailThisSession}).toIgnore;
console.log(ignoreList)
output undefined
请注意,控制台记录 url 变量确实将我想要的值打印到 append 到数组中,我尝试了任何格式文档组合,但我可以在架构图中找到我能想到的架构图完成它的方法! 任何帮助,将不胜感激!
更新,使用承诺也不起作用
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!
无法使用 mongoose 在文档中添加数组元素
const UserSchema = new mongoose.Schema({
...
toIgnore: [{toIgnoreURL: String}]
})
new User({
...,
toIgnore: [] // <-- optional, you can remove it
})
User.findOne({...}).then(user => {
console.log(user.toIgnore)
});
User.update(
{email: emailThisSession},
{$push: {toIgnore: {toIgnoreURL: url}}}
).then(user => {
console.log(user)
})
所以在你的情况下,这是未定义的:
User.findOne({email:emailThisSession}).toIgnore
因为findOne
是异步的。 要获得结果,您可以将其传递给回调,也可以使用承诺( User.findOne({...}).then(user => console.log(user.toIgnore))
)
更新:
同时调整Schema如下:
new Schema({..., toIgnore: []})
这是您更新的问题。 你应该把它改回: toIgnore: [{toIgnoreURL: String}]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.