我的简单问题是:
我在服务器端有一个 Mongoose 对象:
...
项目={
名称:“测试”,
编号:1
}
//项目是 mongo 模式
//id 和 name 在模型中定义 String
和 Number
然后我添加到item
新字段mentions
:
item.mention = [{ id: 1, ... }]
但我无法在客户端提及
。
我的响应代码:
res,json({ status: 1, message: 'success', data: item })
响应为data: { name: "Test", id: 1 }
我不想将提及
添加到我的 mongo 架构中。
那么,我的问题是什么?
我该如何解决这个问题?
谢谢!
最佳答案
问题是 item
是 MongooseDocument ,不是一个普通的 JavaScript 对象。
有多种方法可以实现您想要的目标。
1) 使用 .lean()
Documents returned from queries with the lean option enabled are plain javascript objects, not MongooseDocuments
Model.findOne().lean().exec((err, item) => {
item.mention = [{ id: 1 }];
res.json(item);
});
此选项将提高性能,因为您忽略了创建 Mongoose 文档的开销
2) 使用:.set()
item.set('mention', [{ id: 1}], { strict: false });
4) 使用 spread operator
res.json({
status: 1,
message: 'success',
data: { mention: [{ id: 5 }], ...item }
})
4) 使用 Object.assign
正如 @Alexis Facques 所解释的。
关于node.js - Nodejs 客户端缺少属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49575678/